如果用户在10分钟内没有执行任何操作,是否有销毁会话的选项?
session_start();
// 10 mins in seconds
$inactive = 600;
$session_life = time() - $_SESSION['timeout'];
if($session_life > $inactive) {
session_destroy();
header("Location: logoutpage.php");
}
$_SESSION['timeout']=time();
上面的代码取自这个特定的页面。
尝试将会话超时设置为10分钟。
ini_set('session.gc_maxlifetime',10);
我用以下代码完成了它:
//10 min
if( !isset($_SESSION['logout']) ){
$_SESSION['logout'] = strtotime('+10 minutes', time());
}
if( time() > $_SESSION['logout'])
{
session_destroy();
header("Location: index.php");
}else{
$_SESSION['logout'] = strtotime('+10 minutes', time());
}
//echo date('Y/m/d h:i:s',$_SESSION['logout']);
//echo $_SESSION['logout'];
我修改了上面的答案,它运行良好:
// inactive in seconds
$inactive = 10;
if( !isset($_SESSION['timeout']) )
$_SESSION['timeout'] = time() + $inactive;
$session_life = time() - $_SESSION['timeout'];
if($session_life > $inactive)
{ session_destroy(); header("Location:index.php"); }
$_SESSION['timeout']=time();
在页面中包含以下javascript将通过每秒调用函数CheckIdleTime()
来检查是否处于非活动状态。页面上的活动将_idleSecondsCounter
重置为0。
<script type="text/javascript">
var IDLE_TIMEOUT = 10 * 60; // 10 minutes of inactivity
var _idleSecondsCounter = 0;
document.onclick = function() {
_idleSecondsCounter = 0;
};
document.onmousemove = function() {
_idleSecondsCounter = 0;
};
document.onkeypress = function() {
_idleSecondsCounter = 0;
};
window.setInterval(CheckIdleTime, 1000);
function CheckIdleTime() {
_idleSecondsCounter++;
var oPanel = document.getElementById("SecondsUntilExpire");
if (oPanel)
oPanel.innerHTML = (IDLE_TIMEOUT - _idleSecondsCounter) + "";
if (_idleSecondsCounter >= IDLE_TIMEOUT) {
// destroy the session in logout.php
document.location.href = "logout.php";
}
}
</script>
比较两个请求之间的时间戳,一个来自当前请求,一个存储在会话中。