TP6.0验证码接口

安装验证码功能组件(如果是官网下载的完整版框架,无需安装)

composer require topthink/think-captcha


创建验证码接口

   

/**
     * 获取验证码
     * @return \think\response\Json|void
     */
    public function getcaptcha(){
        //验证码标识
        $uniqid = uniqid((string)mt_rand(100000, 999999));
        //返回数据 验证码图片路径、验证码标识
        $data = [
            'src' => 'http://adminapi.pyg.com'.captcha_src(),
            'uniqid' => $uniqid
        ];
        return success('success',200,$data);
    }


可修改组件源代码如下:

修改底层配置
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,
        ]);
        cache('captcha', [
            'key' => $hash,
        ]); //加上这行代码,便于后续校验验证码
        return [
            'value' => $bag,
            'key'   => $hash,
        ];
    }
 
    /**
     * 验证验证码是否正确
     * @access public
     * @param string $code 用户验证码
     * @return bool 用户验证码是否正确
     */
    public function check(string $code): bool
    {
        if (!cache('captcha')) {
            return false;
        }
 
        $key = cache('captcha')['key'];
 
        $code = mb_strtolower($code, 'UTF-8');
 
        $res = password_verify($code, $key);
 
        if ($res) {
            cache('captcha');
        }
 
        return $res;
    }

————————————————
版权声明:本文为CSDN博主「Doc_ACwhite」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Doc_ACwhite/article/details/122101392

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值