【PHP】TP6.0验证码接口

小破孩
2022-06-27 / 0 评论 / 186 阅读 / 正在检测是否收录...

安装验证码扩展:composer require topthink/think-captcha

创建验证码接口:

    public function setYzm(){
        $captcha_img = Captcha_src();
        $src = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].'/api'.captcha_src();
        ob_clean();    //清除缓冲区,防止出现“图像因其本身有错无法显示'的问题
        $type = getimagesize($src)['mime'];  //获取图片类型
        header("Content-Type:{$type}");
        $imgData = file_get_contents($src); //获取图片二进制流
        $base64String = 'data:' . $type . ';base64,' . base64_encode($imgData);
        return show(200,'请求成功',$base64String);
    }
    可以不用base64处理直接返回验证码地址

    public function checkYzm($yzm){
        if(!Captcha::checkApi($yzm)) throw new Exception('验证码验证失败~');
        return true;
    }

修改底层配置
路径:vendor/topthink/think-captcha/src/Captcha.php

/**
     * 创建验证码
     * @return array
     * @throws Exception
     */
    protected function generate(): array
    {
        $bag = '';
 
        if ($this->math) {
            $this->useZh  = false;
            $this->length = 5;
 
            $x   = random_int(10, 30);
            $y   = random_int(1, 9);
            $bag = "{$x} + {$y} = ";
            $key = $x + $y;
            $key .= '';
        } else {
            if ($this->useZh) {
                $characters = preg_split('/(?<!^)(?!$)/u', $this->zhSet);
            } else {
                $characters = str_split($this->codeSet);
            }
 
            for ($i = 0; $i < $this->length; $i++) {
                $bag .= $characters[rand(0, count($characters) - 1)];
            }
 
            $key = mb_strtolower($bag, 'UTF-8');
        }
 
        $hash = password_hash($key, PASSWORD_BCRYPT, ['cost' => 10]);
 
        $this->session->set('captcha', [
            'key' => $hash,
        ]);
        
        //加上这行代码,便于后续校验验证码
        if(empty(cache($key))){
            cache($key, $hash, 5*60); 
        }else{
            return $this->generate();
        }
        //加上这行代码,便于后续校验验证码
        return [
            'value' => $bag,
            'key'   => $hash,
        ];
    }
 
    /**
     * 验证验证码是否正确
     * @access public
     * @param string $code 用户验证码
     * @return bool 用户验证码是否正确
     */
    public function checkApi(string $code): bool
    {
        if (!cache($code)) {
            return false;
        }
        $key = cache($code);
        $code = mb_strtolower($code, 'UTF-8');
        $res = password_verify($code, $key);
        if ($res) {
            cache($code,NULL);
        }
        return $res;
    }
0

评论 (0)

取消