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

前言:

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

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

<?phpnamespace appmanagecontrol;use 	hinkController;class Main extends Controller{ protected $request; public function _initialize(){ $this->request = 	hinkRequest::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、创建公共控制器(所有需要验证登录的控制器都继承该控制器)

<?phpnamespace appcommoncontrol;use 	hinkController;class AdminBase extends Controller{ protected $request; public function _initialize(){ parent::_initialize();  $this->request = 	hinkRequest::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文件

$.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文件即可,登录页面可不用调用!

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