驗證碼功能組件下載:
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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/389124.html
標籤:其他
上一篇:python的內置裝飾器
下一篇:Monkey基礎
