ThinkPHP5.1 + vue 验证码
super
2020-08-12 11:15
4464
2022-12-1日更新:ThinkPHP6.1+vue验证码
懒得写验证码类,直接用ThinkPHP的
composer require topthink/think-captcha=2.0.*
找到vendor/topthink/think-captcha/src/Captcha.php function entry
line:198
$code = $this->authcode(strtoupper(implode('', $code)));
修改为以下代码:
$code = md5(strtoupper(implode('', $code)));
line:203
Session::set($key . $id, $secode, '');
ob_start();
// 输出图像
imagepng($this->im);
$content = ob_get_clean();
imagedestroy($this->im);
return response($content, 200, ['Content-Length' => strlen($content)])->contentType('image/png');
修改为以下代码
$randomKey = $this::randomCode();
Cache::set($randomKey, $secode, 3600);
ob_start();
// 输出图像
imagepng($this->im);
$content = ob_get_clean();
imagedestroy($this->im);
// 返回base64和key,把key返回到前台,提交表单时需带上key,判断前台输入的验证码是否正确
return ['content' => "data:image/png;base64," . base64_encode($content), 'key' => $randomKey];
Captcha.php新增function randomCode:
/**
* 生成随机码
* @access private
* @author super
* @time 2020-08-12
* @return string
* */
private function randomCode()
{
$randomCode = md5(time() . rand(1000, 9999) . rand(10, 99));
if (Cache::get($randomCode)) {
$this->randomCode();
}
return $randomCode;
}
验证:
/**
* 验证
* @access private
* @author super
* @time 2020-08-12
* @param string $code 用户输入的验证码
* @param string $key 验证码key (生成验证码时有返回)
* @return array
* */
private function checkCode($code, $key)
{
$data = Cache::pull($key);
if (!isset($data['verify_time']) || !isset($data['verify_code'])) return ['code' => 501, 'msg' => '验证码已过期'];
if (time() > $data['verify_time'] + 1800) return ['code' => 501, 'msg' => '验证码已过期'];
$code = md5(strtoupper($code));
if ($code != $data['verify_code']) {
return ['code' => 501, 'msg' => '验证码错误'];
} else {
return ['code' => 200];
}
}
注意:
需修改代码行数可能与上文标注不一致,以实际代码为准
use think\facade\Cache;
文件保存失败问题,请检查服务器文件夹www权限是否可写
0 条讨论