doowebdev/doo-csrf

Doo csrf 是一个简单易用的随机令牌生成器,用于 PHP 脚本以防止 Csrf - 跨站请求伪造。

1.0.0 2014-09-07 01:32 UTC

This package is not auto-updated.

Last update: 2024-09-24 03:40:51 UTC


README

Doo csrf 是一个简单的随机令牌生成器,用于 PHP 脚本来防止 Csrf - 跨站请求伪造。

安装 -

要安装 Doo csrf 的最新版本,只需将其添加到 composer.json 文件中的 require 部分

"doowebdev/doo-csrf": "dev-master"

一旦安装了该包,您需要初始化 Token 类

require 'vendor/autoload.php';

use DooCSRF\Token;

用于生成和检查随机令牌的静态方法

Token::generate(); //Generates a random token string.

Token::check( PLACE-$_POST-NAME-HERE );// Checks if random token is valid.

如何使用 -

假设您正在使用应用程序中的 php 类(您也可以在 php 过程性代码中使用),以下是一个示例

在您的基控制器中

use DooCSRF\Token;

class BaseController{
     
      protected $data = []; // assign $data to an empty array.

      public function __construct(){
      
          //assign the token static method to a varibale, in this case it's the token variable create by the data array
           $this->data['token'] = Token::generate();
      
      }

}


class SomeclassController extends BaseController {

     
     public function someMethod(){
     
           View::display('path/to/a/view', $this->data );//the token variable is past through to the view via the $this->data array.
     }


}

在您的视图中,将 $token 变量添加到表单中的一个隐藏输入中,例如

<form action="/path/to/post/route/or/url" method="post">

<label> someTitle</label>
<input type="text" name ="someName">

<input type="hidden" name="token" value="{{ token }}"> 
<!-- if you using a template engine like Twig, wrap it in the template brackets ( or whatever is given), if not use good old php <?php echo $token; ?> -->

<button type="submit"></button>

</form>

在将接收 post 数据的控制器方法或文件中

use DooCSRF\Token; 

if( Token::check( $_POST['token'] ) ){

     //Protected area. Do somthing,  database inserts etc..
}

就这样,简单又方便!