TP登陆验证码代码

public function chkcode()
{
$Verify=new ThinkVerify(array(
'fontSize'=>30, //验证码字体大小
'length' =>4, //验证码位数
'useNoise' =>TRUE, //关闭验证码杂点
));
$Verify->entry();
}

<tr>
<td>验证码:</td>
<td>
<input type="text" name="chkcode" class="capital" />
</td>
</tr>
<tr>
<td colspan="2" align="right">
<img style="cursor:pointer;" onclick="this.src='<?php echo U('chkcode'); ?>#'+Math.random();" src="<?php echo U('chkcode'); ?>" />
</td>
</tr>

在模型中的代码

    

<?php
namespace AdminModel;
use ThinkModel;
class AdminModel extends Model
{
protected $insertFields = array('username','password','cpassword','chkcode');   
protected $updateFields = array('id','username','password','cpassword');

//添加和修改管理员时使用的表单验证规则
protected $_validate = array(
array('username', 'require', '用户名不能为空!', 1, 'regex', 3),
array('username', '1,30', '用户名的值最长不能超过 30 个字符!', 1, 'length', 3),
//第六个参数:规则什么时候生效:1 添加时生效,2 修改时生效,3,所有情况都生效
array('password', 'require', '密码不能为空!', 1, 'regex', 1),
array('cpassword', 'password', '两次密码输入不一致!', 1, 'confirm', 3),
array('username', '', '用户名已经存在!', 1, 'unique', 3),
);

//为登陆的表单定义一个验证规则
public $_login_validata=array(
array('username','require','用户名不能为空',1),
array('password','require','密码不能为空',1),
array('chkcode','require','验证码不能为空',1),
array('chkcode','check_verify','验证码错误',1,'callback'),
);

//验证码是否正确
function check_verify($code,$id='')
{
$verify=new ThinkVerify();
return $verify->check($code,$id);
}

public function login()
{
//从模型中获取用户名和密码
$username= $this->username;
$password=$this->password;
//先查询这个用户名是否存在
$user=$this->where(array(
'username'=>array('eq',$username),
))->find();

if($user)
{
if($user['password'] == md5($password))
{
//登录成功保存session
session('id',$user['id']);
session('username',$user['username']);
return true;
}
else{
$this->error="用户名或密码错误";
return false;
}
}
else
{
$this->error="用户名不存在";
return false;
}
}

控制器中的登陆代码

public function login()
{
if(IS_POST)
{
$model=D('admin');
//接收表单并且验证表单
if($model->validate($model->_login_validata)->create())
{
if($model->login())
{
$this->success('登陆成功!',U('Index/index'));
exit;
}
}
$this->error($model->getError());
}
$this->display();

}

世上无难事,只怕有心人......
原文地址:https://www.cnblogs.com/gooderic/p/5675074.html