Thinkphp中封装好了验证码的使用和验证方式,我们这里不讨论验证码的实现,利用Thinkphp提供给我们的方法来实现验证码,需要在php文件头声明use Think\verify
1、在文档中我们可以看到验证码最简单的生成方式:
$Verify = new \Think\Verify();
$Verify->entry();
只要在类中使用这个方法即可简单的生成验证码,如下图所示:
当然这是一个简单的验证码,Thinkphp给我们提供了很多验证码的配置,在开发文档中都已经说明,我在我的验证码中加入以下配置:
public function verify(){
$config = [
'fontSize' => 20, // 验证码字体大小
'length' => 4, // 验证码位数
'imageH' => 34
];
$Verify = new Verify($config);
$Verify->entry();
// $this->display();
}
即可显示自己定义的验证码。
2、添加验证码的验证方法
public function check_code($code){
$verify = new \Think\Verify();
return $verify->check($code);
}
$code是调用该方法是传入的你输入的验证码,调用该方法:
public function do_login(){
//获取用户名和密码和数据库比对
$username=$_POST['username'];
$password=$_POST['password'];
$code=I('code');
// dump(md5($code));
// dump($_SESSION);
// dump($_SESSION['verify_code']);
if ($this->check_code($code)==false){
$this->error('验证码错误');
}
$m=M('User');
$where['username']=$username;
$where['password']=$password;
$i=$m->where($where)->count();
if ($i>0){
$this->redirect('User/index');
}
else{
$this->error('该用户不存在');
}
}
到此验证码可以进行验证。