我正在使用会话进行用户登录和注销。我要求在用户不活动 30 分钟后,他/她必须自动注销。我搜索并尝试了一些解决方案,但没有奏效。我尝试了以下解决方案:
解决方案1:
if(time() - $_SESSION['timestamp'] > 900) { //subtract new timestamp from the old one
echo"<script>alert('15 Minutes over!');</script>";
unset($_SESSION['email'], $_SESSION['user_id'], $_SESSION['timestamp']);
session_destroy();
$_SESSION['logged_in'] = false;
header("Location: " . index.php); //redirect to index.php
exit;
} else {
$_SESSION['timestamp'] = time(); //set new timestamp
}
解决方案2:
function auto_logout($field)
{
$t = time();
$t0 = $_SESSION[$field];
$diff = $t - $t0;
if ($diff > 3000 || !isset($t0))
{
return true;
}
else
{
$_SESSION[$field] = time();
}
}
if(auto_logout("email"))
{
session_unset();
session_destroy();
header('Location: index.php');
exit;
}
它们都不起作用,任何人都可以告诉我如何跟踪用户的上次活动,并在超过 30 分钟时与当前时间检查该时间并使该用户注销?
我认为
这可能会有所帮助:如何在 30 分钟后使 PHP 会话过期?
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
// last request was more than 30 minutes ago
session_unset(); // unset $_SESSION variable for the run-time
session_destroy(); // destroy session data in storage
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
如果要查找活动,可以使用如下所示的javascript,然后重定向到注销页面以清除会话。 在这里我放了 5 秒的不活动
var t;
window.onload = resetTimer();
// DOM Events
document.onmousemove = resetTimer();
document.onkeypress = resetTimer();
console.log('loaded');
function logout() {
alert("You are now logged out.")
//location.href = 'logout.php'
}
function resetTimer() {
clearTimeout(t);
t = setTimeout(logout, 5000)
}