1.在Common/function.php中
/**
* 异位或加密字符串
* @param [String] $value [需要加密或解密的字符串]
* @param [integer] $type [0:加密 1:解密]
* @param [String] [返回加密或解密的字符串]
*/
function encryption($value, $type = 0){
$key = md5(C('ENCRYPTION_KEY'));
//加密
if(!$type){
return str_replace('=', '', base64_encode($value ^ $key));
}
//解密
$value = base64_decode($value);
return $value ^ $key;
}
2.当勾选自动登陆时
//登陆处理
public function signIn(){
if(!IS_AJAX){
$this->redirect('Login/index');
}
$array = array();
$username = trim(I('post.username'));
$password = trim(MD5(I('post.password')));
$auto = I('post.auto');
$admin = M('admin');
$uc = $admin->where(array('username'=>$username))->find();
if($uc){
if($uc['password'] == $password){
$_SESSION['id'] = $uc['id'];
$_SESSION['username'] = $uc['username'];
//自动登陆功能实现
if($auto){
$account = $uc['username']; //取得用户名
$ip = get_client_ip(); //获取客户端IP
$value = $account . '|' . $ip;
$value = encryption($value);
cookie('auto',$value);
}
$array['msg'] = 1;
$array['url'] = '/Admin/Index/index';
}else{
$array['msg'] = '密码错误';
}
}else{
$array['msg'] = '账号不存在';
}
exit(json_encode($array));
}
}
3.公共头部判断是否上次登录
//自动登陆处理
if(isset($_COOKIE['auto']) && !isset($_SESSION['id'])){
$value = explode('|', encryption($_COOKIE['auto'], 1));
$ip = get_client_ip();
//本次登陆IP和上次登陆IP相匹配
if($ip == $value['1']){
$where = array('username' => $value['0']);
$user = M('admin')->where($where)->find();
//查看是否存在这个用户或者这个用户被锁定
if($user){
$_SESSION['id'] = $user['id'];
}
}
}
4.视图页面代码
<input type="checkbox" name='auto' checked='1' class='auto' id='auto'/>
<label for="auto">下次自动登录</label>