首页 > 编程学习 > laravel+mews/captcha 打开页面后的首次验证码总是验证失败的问题解决

出现问题的原因

验证码获取后,还有其他的接口请求,导致验证码的缓存被覆盖(参考文章:Laravel Session 遇到的坑)

解决办法

修改vendor/mews/captcha/src/Captcha.php源码,将原本的在session保存验证码改为Cache中保存,具体修改如下

修改generate()
将原本的

$this->session->put('captcha', [
    'sensitive' => $this->sensitive,
    'key' => $hash,
    'encrypt' => $this->encrypt,
    'value'=>$key
]);

改为

Cache::put('captcha:'.session()->getId(), json_encode([
    'sensitive' => $this->sensitive,
    'key' => $hash,
    'encrypt' => $this->encrypt,
    'value'=>$key
]), 600);

修改check()
将原本的

if (!$this->session->has('captcha')) {
    return false;
}

$key = $this->session->get('captcha.key');
$sensitive = $this->session->get('captcha.sensitive');
$encrypt = $this->session->get('captcha.encrypt');

改为

if (!Cache::has('captcha:'.session()->getId())) {
    return false;
}
$data = json_decode(Cache::get('captcha:'.session()->getId()));
$key = $data->key;
$sensitive = $data->sensitive;
$encrypt = $data->encrypt;
Copyright © 2010-2022 mfbz.cn 版权所有 |关于我们| 联系方式|豫ICP备15888888号