《PHP學習:php登錄超時檢測功能實例詳解》要點:
本文介紹了PHP學習:php登錄超時檢測功能實例詳解,希望對您有用。如果有疑問,可以聯系我們。
PHP實戰php登錄超時檢測功能實例詳解
PHP實戰前言:
PHP實戰php登錄超時問題,當用戶超過一定時間沒有操作頁面時自動退出登錄,原理是通過js進行訪問判斷的!代碼如下(以thinkphp5.0版本為例)
PHP實戰1、創建登錄版塊控制器:
PHP實戰
<?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();
//這里為登錄驗證(自行補充)
.......
//通過登錄提交的信息獲取數據庫中的用戶,并記錄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]);
}
}
}
PHP實戰2、創建公共控制器(所有需要驗證登錄的控制器都繼承該控制器)
PHP實戰
<?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);
}
}
}
PHP實戰3、js文件
PHP實戰
$.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;
}
});
}
PHP實戰最后在所有的頁面調用上訴js文件即可,登錄頁面可不用調用!
PHP實戰感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
轉載請注明本頁網址:
http://www.snjht.com/jiaocheng/1348.html