Home >Backend Development >PHP Tutorial >Reasons and solutions for TP6 verification code verification failure

Reasons and solutions for TP6 verification code verification failure

silencement
silencementforward
2020-01-26 22:16:165275browse

Reasons and solutions for TP6 verification code verification failure

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

composer require topthink/think-captcha

The controller introduces

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

Verify verification code

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

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;
}

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
]

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!

Statement:
This article is reproduced at:www.liqingbo.cn. If there is any infringement, please contact admin@php.cn delete