安装验证码功能组件(如果是官网下载的完整版框架,无需安装)
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;
}
|