表单令牌

验证规则支持对表单的令牌进行验证,首先需要在表单中增加一个隐藏域:

  1. <input type="hidden" name="__token__" value="<?php echo $request->token(); ?>">

然后在验证规则中,添加 token 验证规则即可,例如:

  1. namespace app\index\validate;
  2. use ginkgo\Validate;
  3. class User extends Validate {
  4. protected $rule = array(
  5. 'email' => array(
  6. 'format' => 'email',
  7. ),
  8. '__token__' => array(
  9. 'require' => true,
  10. 'token' => true,
  11. ),
  12. );
  13. }

如果令牌名称不是 __token__,则表单需要改为:

  1. <input type="hidden" name="__hash__" value="<?php echo $request->token(); ?>">

验证器中改为:

  1. namespace app\index\validate;
  2. use ginkgo\Validate;
  3. class User extends Validate {
  4. protected $rule = array(
  5. 'email' => array(
  6. 'format' => 'email',
  7. ),
  8. '__hash__' => array(
  9. 'require' => true,
  10. 'token' => true,
  11. ),
  12. );
  13. }

如果需要自定义令牌生成规则,可以调用 Request 类的 token 方法,例如:

  1. namespace app\index\ctrl;
  2. use ginkgo\Ctrl;
  3. class Index extends Ctrl {
  4. public function index() {
  5. $token = $this->obj_request->token('__token__', 'sha1');
  6. $this->assign('token', $token);
  7. return $this->fetch();
  8. }
  9. }

然后在模板表单中使用:

  1. <input type="hidden" name="__token__" value="<?php echo $token; ?>">