Home > Backend Development > PHP Tutorial > A must see! Reasons and solutions for TP6 verification code verification failure

A must see! Reasons and solutions for TP6 verification code verification failure

silencement
Release: 2023-04-08 09:30:02
forward
5346 people have browsed it

A must see! 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

Controller introduction

use think\captcha\facade\Captcha;
Copy after login

Generate 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

It can be seen from the above check method that verification code verification requires session, and Thinkphp6 is not enabled by default. It needs to be initialized according to the manual.

Find the global middle in the application app directory File middleware.php, just turn on the code commented below\think\middleware\SessionInit::class

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

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

Related labels:
tp6
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