微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php登录超时检测功能实例详解

PHP登录超时检测功能实例详解

前言:

PHP登录超时问题,当用户超过一定时间没有操作页面自动退出登录,原理是通过js进行访问判断的!代码如下(以thinkPHP5.0版本为例)

1、创建登录版块控制器:

rush:PHP;"> class Main extends Controller{

protected $request;

public function _initialize(){
$this->request = \think\Request::instance();
}

public function login(){
if($this->request->method() == "POST"){
$data = $this->request->param();
//这里为登录验证(自行补充)
.......
//通过登录提交的信息获取数据库中的用户,并记录ID($id)
cookie('ADMIN_ID',$result["id"]);//cookie缓存
cookie('LOGIN_TIME',Request::instance()->time()+3600);//记录登录时间,并缓存1小时

}
return view();
}

// 检测是否登录超时(js调用,url为:http://您的域名/manage/main/loginLosetime
public function loginLosetime(){
$logintime = cookie('LOGIN_TIME');
$time = request()->time();
if($time > $logintime){
return json(['code'=>1,'msg'=>'登录超时!','url'=>url('main/login')]);
}else{
return json(['code'=>0]);
}
}

}

2、创建公共控制器(所有需要验证登录的控制器都继承该控制器)

rush:PHP;"> namespace app\common\control;
use \think\Controller;
class AdminBase extends Controller{
protected $request;
public function _initialize(){
parent::_initialize();
$this->request = \think\Request::instance();
$this->checkLogin();//检测登录
$this->doAction();//记录动作
}
protected function checkLogin(){

$cookie_admin_id = cookie('ADMIN_ID');
if(!empty($cookie_admin_id)){
//获取登录用户信息
.......
}else{
if($this->request->isAjax()){
return $this->error('您还没有登录!',url('main/login'));
}else{
header("Location:".url("main/login"));
exit();
}
}
}
// 页面操作记录
protected function doAction(){
$logintime = cookie('LOGIN_TIME');//获取缓存登录超时时间
$time = request()->time();//当前时间
//判断当前时间是否大于缓存时间 或者 超时时间小于60秒后,自动多加1个小时时间
if($time > $logintime || ($time - $logintime) < 60){
$newLogintime = $logintime + 3600;
cookie('LOGIN_TIME',$newLogintime);
}
}
}

3、js文件

rush:js;"> $.ajaxSetup({ cache: false }); $(function(){ setInterval(function() { loginLosetime() },360000);//设置1小时自动执行 loginLosetime 函数(时间可自行调整) }); // 登录超时检测 function loginLosetime(){ $.get(AJAX_URL+'main/loginLosetime',function(res){ if(res.code == 1){ window.location.href = res.url; } }); }

最后在所有的页面调用上诉js文件即可,登录页面可不用调用

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐