TP5验证码使用

首先使用Composer安装think-captcha扩展包:

composer require topthink/think-captcha

完成上述操作,会在以下目录中出现 captcha 的扩展包

..\vendor\topthink\think-captcha
验证码配置

然后在应用配置文件中添加验证码的配置参数

'captcha'  => [
        // 验证码字符集合
        'codeSet'  => '2345678abcdefhijkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY', 
        // 验证码字体大小(px)
        'fontSize' => 25, 
        // 是否画混淆曲线
        'useCurve' => true, 
         // 验证码图片高度
        'imageH'   => 30,
        // 验证码图片宽度
        'imageW'   => 100, 
        // 验证码位数
        'length'   => 5, 
        // 验证成功后是否重置        
        'reset'    => true
],

前端设置

在前端页面需要显示验证码的位置,补充 {:captcha_img()} 即可,个人代码举例如下:

<p class="pass-form-item">
        <label class="pass-label">验证码</label>
        <input type="text" name="verifyCode" class="pass-text-input " placeholder="请输入验证码">
      <div>{:captcha_img()}</div>
      </p>

captcha 扩展包代码优化

如果按照上述操作,显示的验证码图片并不能点击刷新,可自己根据需求进行刷新功能设计;或者,建议进行下面的代码优化:

function captcha_img($id = "")
{
    $js_src = "this.src='".captcha_src()."'";
    return '<img src="' . captcha_src($id) . '" alt="点击更新验证码"
     onclick="'.$js_src.'" />';
    //return '![](' . captcha_src($id) . ')';
}
  • 打开 ..\vendor\topthink\think-captcha\src\helper.php 文件,替换上面的 captcha_img() 方法代码.
  • 此时的验证码图片即可实时刷新.

 后台代码验证

根据前端请求而来的 verifyCode 数据,调用 helper.php 中的captcha_check() 方法,进行验证。

 if(request()->isPost()){
            $data = input('post.');
            if(!captcha_check($data['verifyCode'])) {
                // 校验失败
                $this->error('验证码不正确');
            }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

提示

  • 建议阅读 ..\vendor\topthink\think-captcha\src\helper.php 文件,及 Captcha.php ,可以进行样式的自定义.
  • 如果前端 {:captcha_img()}有传值 id,那么后台 captcha_check() 验证也需要相应的 id 参数区分。
  • 验证结果,普遍使用 ajax 请求,以满足用户顺畅的体验.

今天试用的一种方法是将Tp3.2的Verify.php类移植进来,但是效果不理想,因为tp5的各种函数改变很大,不容易无缝移植,而且自己将生成的验证码存入session与去出方法都改写了。所以不建议使用。

猜你喜欢

转载自blog.csdn.net/echo_hello_world/article/details/80345660