不言不语

您现在的位置是: 首页 >  PHP

PHP

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

2022-06-05PHP
Session功能默认是没有开启的(API应用通常不需要使用Session),如果你需要使用Seesion,需要在全局的中间件定义文件中加上下面的中间件定义:'think\middleware\SessionInit'

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

composer require topthink/think-captcha


控制器引入

use think\captcha\facade\Captcha;


生成验证码

public function verify()
{
    return Captcha::create();
}


验证验证码

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


check的方法

/**
 * 验证验证码是否正确
 * @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;
}

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

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

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



文章评论