1.确定项目目录》vendor》topthink》think-captcha目录存在

2.在config中添加验证码配置
//验证码配置
        ‘captcha‘ => [
    // 验证码字符集合
            ‘codeSet‘ => ‘2345678abcdefhijkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY‘,
    // 验证码字体大小(px)
            ‘fontSize‘ => 20,
    // 是否画混淆曲线
            ‘useCurve‘ => true,
    // 验证码图片高度
            ‘imageH‘ => 42,
    //是否添加杂点
            ‘useNoise‘=>true,
    // 验证码图片宽度
            ‘imageW‘ => 148,
    // 验证码位数
            ‘length‘ => 4,
    // 验证成功后是否重置
            ‘reset‘ => true
        ],
3.模板captcha.html里输出验证码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>验证码</title> <script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script> </head> <body> 输入验证码: <div> <img id="verify_img" src="{:captcha_src()}" alt="验证码" onclick="refreshVerify()"> <a href="javascript:refreshVerify()">点击刷新</a> </div> <form class="layui-form" action="" > <input type="text" name = "verify"> <button class="layui-btn" lay-filter="checkcaptcha" lay-submit="" id="checkcaptcha" > 保存 </button> </form> <script> function refreshVerify() { var ts = Date.parse(new Date())/1000; var img = document.getElementById(‘verify_img‘); img.src = "{:captcha_src()}"; } </script> <script> $(function () { $("#checkcaptcha").on("click",function(){ $.ajax({ type: ‘POST‘, url: "{:url(‘test/checkcaptcha‘)}", data: $(".layui-form").serialize(), dataType: "json", async: false, error: function(request) { alert("发送请求失败!"); }, success: function(data){ console.log(data); if (data.status == 1) { alert(data.message); } else { alert(data.message); } } }); }) }) </script> </body> </html>
4.在控制器Test.php中书写验证码检验逻辑
//检验验证码 
 public function checkcaptcha()
    {
       $status=1;
        $captcha = input(‘verify‘);
        if(!captcha_check($captcha)){
            //验证码错误
           $message=‘验证码错误‘;
        }else{
            //验证码正确
            $message=‘验证码正确‘;
        }
        return [‘status‘=> $status, ‘message‘=> $message];
    }