tp5下直接生成的验证码, 有些时候会不符合我们的要求, 这时需要用到自定义代码的生成, 然而TP5文档手册写的实例不是非常清晰, 很多人看了容易云里雾里, 这里分享给大家 验证码的生成,调用,及验证方法
1. 引入Captcha及生成自定义函数代码
namespace app\index\controller; use think\Controller; use think\Config; use think\Validate; use think\captcha\Captcha; /*use think\Request;*/ class Stu extends Controller{ public function getCode(){ $config = [ // 验证码字体大小 'fontSize' => 30, // 验证码位数 'length' => 3, // 关闭验证码杂点 'useNoise' => false, 'useZh' => true ]; $captcha = new Captcha($config); return $captcha->entry(); } }
2. 视图文件引用
<img src="<?php echo url("stu/getcode"); ?>" onclick="this.src='<?php echo url("stu/getcode"); ?>?id='+Math.random();" />3. 使用TP 验证码验证
$validate = new Validate([ '__token__' => 'require|token' ]); $data = [ 'captcha' => $this->request->param("code") ]; if (!$validate->check($data)) { echo($validate->getError()); }