验证码是框架内置的图形验证码,基于 GD 生成,答案存 Session,尺寸、位数、过期时间都在配置里。
配置
// config/app.php
'captcha' => [
'fontsize' => 20,
'height' => 32,
'width' => 150,
'length' => 4,
'ttf' => '6.ttf',
'expire' => 60, // 秒
],
输出图片
/**
* @RequestMapping(route="/user/code", title="图形验证码")
*/
public function code()
{
// 直接输出图片,不需要 return
$this->captcha();
}
前端用 <img src="/user/code?t=时间戳">,点一下换一张就改 t。
校验
$code = (string) Request::post('code', '');
if (!$this->captcha_check($code)) {
return $this->error('验证码错误', '/login');
}
captcha_check() 校验后即销毁,同一个验证码不能用两次——包括刷新页面重试,必须重新取图。
多场景共存
登录和评论各要一个验证码时,用第二个参数区分 Session 键:
$this->captcha(1, 'login'); // 登录用
$this->captcha_check($code, 'login');
$this->captcha(1, 'comment'); // 评论用
$this->captcha_check($code, 'comment');
坑
- Session 没生效:验证码依赖 Session,Redis 不通时
captcha_check()永远返回 false; - 浏览器缓存:不加
?t=随机参数,点「换一张」图片不变; - 过期时间:默认 60 秒,用户慢慢填就失效了,表单页可以调到 300;
- 接口场景(App、小程序)不要用图形验证码,改用短信或 Token。