其实thinkphp5验证码也简单的了,不过首先需要保证你的一下扩展包。
不过只要你安装的是完整版的话系统都会自带有的啦,因为我这个就是完整版的。
好啦,有了这个扩展包了之后直接在模板文件里面放一个验证码标签就立马见效。
标签如下:
<div>{:captcha_img()}</div>
<h2>验证码</h2>
<form method="post" action="{:url('check')}">
输入验证码:<input type="text" class="text" name="captcha">
<div id="captcha_image" onclick="code();">{:captcha_img()}</div>
<span style="color:red;">{$codeerror}</span><br/>
<input type="submit" value="提交"/>
</form>
<!---这个js方法是 切换验证码图片用的--->
<script>
function code(){
var querysrc=document.getElementById('captcha_image');
querysrc.getElementsByTagName('img')[0].src='http://localhost{:captcha_src()}?'+Math.random();
}
</script>
或者也可以用另一个标签:
<div><img src="{:captcha_src()}" alt="captcha" /></div>
<h2>验证码</h2>
<form method="post" action="{:url('check')}">
输入验证码:<input type="text" class="text" name="captcha">
<!---这个方法写切换验证码图片比较方便,直接onclick 一行代码搞定 -->
<div ><img src="{:captcha_src()}" onclick="this.src='http://localhost{:captcha_src()}?'+Math.random()" alt="captcha" /></div>
<span style="color:red;">{$codeerror}</span><br/>
<input type="submit" value="提交"/>
</form>
这两个都是一样的效果。
验证码的配置
需要在application/config.php配置文件里面配置一下验证码的几个必要的参数,因为默认的可能不是你想要的样子。比如验证码的大小啊还有验证码需要几位数之类的。
//验证码配置
'captcha'=>[
//字体大小
'fontSize'=>15,
//验证码长度(位数)
'length'=>4,
//使用中文验证码
// 'useZh'=>true,
],
验证码的配置参数
参数 | 描述 | 默认 |
---|---|---|
codeSet | 验证码字符集合 | 略 |
expire | 验证码过期时间(s) | 1800 |
useZh | 使用中文验证码 | false |
zhSet | 中文验证码字符串 | 略 |
useImgBg | 使用背景图片 | false |
fontSize | 验证码字体大小(px) | 25 |
useCurve | 是否画混淆曲线 | true |
useNoise | 是否添加杂点 | true |
imageH | 验证码图片高度,设置为0为自动计算 | 0 |
imageW | 验证码图片宽度,设置为0为自动计算 | 0 |
length | 验证码位数 | 5 |
fontttf | 验证码字体,不设置是随机获取 | 空 |
bg | 背景颜色 | [243, 251, 254] |
reset | 验证成功后是否重置 | true |
下面是控制器的代码,在控制器里面除了验证规则需要写点代码之外其他不需要的可以不写。因为我这里主要讲的是验证码其他不关系到验证码的东西没有,所以除了验证规则之外控制器可以是空的。
<?php
namespace app\index\controller;
use think\Controller;
//引入验证
use think\Validate;
class Index extends Controller
{
/**
* @param string $name
*/
public function index()
{
return $this->fetch();
}
//检查验证码
public function check($captcha=''){
$data['captcha' ]=$captcha;
//实例化验证规则
$validate = new Validate([
'captcha|验证码'=>'require|captcha',
]);
//检查验证结果
if(!$validate->check($data)){
$this->assign('codeerror',$validate->getError());
}else{
$this->assign('codeerror',"验证成功");
}
return $this->fetch("index");
/* $captcha=new \think\captcha\Captcha();
if(!$captcha->check($code)){
$this->error('验证码错误');
}else{
$this->success('验证码正确');
}*/
}
}
?>
好啦,现在可以提交一下检验成果。
看到输出结果了没有,这说明你已经成功了。