一、引入模块
使用composer安装
composer require topthink/think-captcha
二、前端引用
在验证码模块的helper.php文件中,修改验证码样式:
function captcha_img($width='',$height='',$id = '', $domid = ''): string
{
$src = captcha_src($id);
$domid = empty($domid) ? $domid : "id='" . $domid . "'";
$style="";
if($height&&$width){
$style='width="'.$width.'";hight="'.$height.'"';
}
return "<img src='{$src}' $style alt='captcha' " . $domid . " οnclick='this.src=\"{$src}?\"+Math.random();' />";
}
在页面二维码图片处写入:
<div class="validateImg" >{:captcha_img(144,50)}</div>
三、后端验证
首先开启session,在全局中间件中,设置:
'think\middleware\SessionInit'
然后在php代码中验证,代码为:
//校验验证码是否正确
if(!captcha_check($captcha)){
$res=[
'status'=>400,
'msg'=>'验证码不正确!'
];
return json($res);
}