当前位置:首页 > CMS教程 > Thinkphp > 列表

TP6验证码验证失败的原因以及解决办法

发布:smiling 来源: PHP粉丝网  添加日期:2022-05-29 07:52:48 浏览: 评论:0 

首先使用Composer安装think-captcha扩展包:

composer require topthink/think-captcha

控制器引入

use think\captcha\facade\Captcha;

生成验证码

  1. public function verify() 
  2.  
  3.  
  4.     return Captcha::create(); 
  5.  

验证验证码

  1. if( !Captcha::check($vercode)) { 
  2.  
  3.     return json(['code'=>1001, 'msg'=>'验证码错误'); 
  4.  

check的方法

  1. /** 
  2.  
  3.  * 验证验证码是否正确 
  4.  
  5.  * @access public 
  6.  
  7.  * @param string $code 用户验证码 
  8.  
  9.  * @return bool 用户验证码是否正确 
  10.  
  11.  */ 
  12.  
  13. public function check(string $code): bool 
  14.  
  15.  
  16.     if (!$this->session->has('captcha')) { 
  17.  
  18.         return false; 
  19.  
  20.     } 
  21.  
  22.    
  23.  
  24.     $key = $this->session->get('captcha.key'); 
  25.  
  26.    
  27.  
  28.     $code = mb_strtolower($code'UTF-8'); 
  29.  
  30.    
  31.  
  32.     $res = password_verify($code$key); 
  33.  
  34.    
  35.  
  36.     if ($res) { 
  37.  
  38.         $this->session->delete('captcha'); 
  39.  
  40.     } 
  41.  
  42.    
  43.  
  44.     return $res
  45.  

从以上check方法可以看出来验证码验证是需要session的,而Thinkphp6默认是不开启的,需要根据手册初始化一下。

在应用app目录下找到全局中间件middleware.php文件,把下面注释的代码\think\middleware\SessionInit::class开启就行了。

  1. // 全局中间件定义文件 
  2.  
  3. return [ 
  4.  
  5.     // 全局请求缓存 
  6.  
  7.     // \think\middleware\CheckRequestCache::class, 
  8.  
  9.     // 多语言加载 
  10.  
  11.     // \think\middleware\LoadLangPack::class, 
  12.  
  13.     // Session初始化 
  14.  
  15.      \think\middleware\SessionInit::class 
  16.  
  17. ]

Tags: TP6验证码验证失败

分享到: