欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

php登錄超時檢測功能實例詳解

 更新時間:2017年03月21日 10:29:21   作者:Mr_Azaz  
這篇文章主要介紹了php登錄超時檢測功能實例詳解的相關資料,需要的朋友可以參考下

php登錄超時檢測功能實例詳解

前言:

php登錄超時問題,當用戶超過一定時間沒有操作頁面時自動退出登錄,原理是通過js進行訪問判斷的!代碼如下(以thinkphp5.0版本為例)

1、創(chuàng)建登錄版塊控制器:

<?php
namespace app\manage\control;
use \think\Controller;

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();
   //這里為登錄驗證(自行補充)
   .......
   //通過登錄提交的信息獲取數(shù)據(jù)庫中的用戶,并記錄ID($id)
   cookie('ADMIN_ID',$result["id"]);//cookie緩存
   cookie('LOGIN_TIME',Request::instance()->time()+3600);//記錄登錄時間,并緩存1小時

 }
 return view();
 }
 
 // 檢測是否登錄超時(js調(diào)用,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、創(chuàng)建公共控制器(所有需要驗證登錄的控制器都繼承該控制器)

<?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文件

$.ajaxSetup({
 cache: false
});
$(function(){
 setInterval(function() {
 loginLosetime()
 }, 360000);//設置1小時自動執(zhí)行 loginLosetime 函數(shù)(時間可自行調(diào)整)
});
// 登錄超時檢測
function loginLosetime(){
 $.get(AJAX_URL+'main/loginLosetime',function(res){
 if(res.code == 1){
 window.location.href = res.url;
 }
 });
}

最后在所有的頁面調(diào)用上訴js文件即可,登錄頁面可不用調(diào)用!

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

相關文章

最新評論