表單令牌
驗證規(guī)則支持對表單的令牌驗證,首先需要在你的表單里面增加下面隱藏域:
<input type="hidden" name="__token__" value="{$Request.token}" />
或者
{:token()}
然后在你的驗證規(guī)則中,添加token
驗證規(guī)則即可,例如,如果使用的是驗證器的話,可以改為:
protected $rule = [
'name' => 'require|max:25|token',
'email' => 'email',
];
如果你的令牌名稱不是__token__
,則表單需要改為:
<input type="hidden" name="__hash__" value="{$Request.token.__hash__}" />
或者:
{:token('__hash__')}
驗證器中需要改為:
protected $rule = [
'name' => 'require|max:25|token:__hash__',
'email' => 'email',
];
如果需要自定義令牌生成規(guī)則,可以調(diào)用Request
類的token
方法,例如:
namespace app\index\controller;
use think\Controller;
class Index extends Controller
{
public function index()
{
$token = $this->request->token('__token__', 'sha1');
$this->assign('token', $token);
return $this->fetch();
}
}
然后在模板表單中使用:
<input type="hidden" name="__token__" value="{$token}" />
或者不需要在控制器寫任何代碼,直接在模板中使用:
{:token('__token__', 'sha1')}
文檔最后更新時間:2018-04-26 10:48:34
未解決你的問題?請到「問答社區(qū)」反饋你遇到的問題