我正在使用会话进行用户登录&登出。我要求在用户不活动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分钟检查当前时间的时间并让该用户注销?
答案 0 :(得分:1)
如果要查找活动,可以使用下面的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)
}
答案 1 :(得分:1)
我认为这可能有所帮助:How do I expire a PHP session after 30 minutes?
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