TP6.0框架-----通过接口返回前端验证码
验证码功能组件下载:
composer require topthink/think-captcha
配置路由:(因为是后端返回前端验证码,会涉及到跨域问题,所以需要加上最后一个指向)
Route::get(getCaptcha,Login/getCaptcha)->allowCrossDomain(); //如果需要更改验证码相关配置,则需要加下面的路由 Route::get(captcha/:id, "\think\captcha\CaptchaController@index");
(目前还不清楚为什么要加第二行的路由,如果有知道的小伙伴,希望能够留言评论,谢谢!)
如果需要更改验证码相关配置,修改文件:app/config/captcha.php
控制器:(域名自行更改)
public function getCaptcha()
{
//验证码标识
$uniqid = uniqid((string)mt_rand(10000, 99999));
//返回数据 验证码图片路径、验证码标识
$data = [
src => "http://adminapi.pyg.com" . captcha_src($uniqid),
uniqid => $uniqid
];
return success(200,ok,$data);
}
接口测试:Postman(接口自行修改)
http://adminapi.pyg.com/captcha
可修改组件源代码如下: 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,
]);
//因为是前后端分离,后端存储session,前端获取不到,所以需要缓存来存取验证码信息
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;
}
上一篇:
Python 安装包管理工具 pip
下一篇:
Charles-解决unknown的问题
