Reasons and solutions for TP6 verification code verification failure

silencement
Release: 2023-04-08 10:34:01
forward
5230 people have browsed it

Reasons and solutions for TP6 verification code verification failure

First use Composer to install the think-captcha extension package:

composer require topthink/think-captcha
Copy after login

The controller introduces

use think\captcha\facade\Captcha;
Copy after login
to generate the verification code
public function verify()
{
    return Captcha::create();
}
Copy after login

Verify verification code

if( !Captcha::check($vercode)) {
    return json(['code'=>1001, 'msg'=>'验证码错误');
}
Copy after login

Check method

/**
 * 验证验证码是否正确
 * @access public
 * @param string $code 用户验证码
 * @return bool 用户验证码是否正确
 */
public function check(string $code): bool
{
    if (!$this->session->has('captcha')) {
        return false;
    }
 
    $key = $this->session->get('captcha.key');
 
    $code = mb_strtolower($code, 'UTF-8');
 
    $res = password_verify($code, $key);
 
    if ($res) {
        $this->session->delete('captcha');
    }
 
    return $res;
}
Copy after login

From the above check method, we can see that verification code verification requires session, and Thinkphp6 defaults to If it is not enabled, you need to initialize it according to the manual.

Find the global middleware middleware.php file in the application app directory, and enable the code \think\middleware\SessionInit::class commented below.

// 全局中间件定义文件
return [
    // 全局请求缓存
    // \think\middleware\CheckRequestCache::class,
    // 多语言加载
    // \think\middleware\LoadLangPack::class,
    // Session初始化
     \think\middleware\SessionInit::class
]
Copy after login

The above is the detailed content of Reasons and solutions for TP6 verification code verification failure. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:www.liqingbo.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template