如何在 30 分钟不活动后让用户注销?

how to make user logout after 30 mins of inactivity?

我正在使用会话进行用户登录和注销。我有一个要求,在 activity he/she 中的用户 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;
}

他们都没有工作,谁能告诉我如何跟踪用户的最后 activity 并在超过 30 分钟时检查该时间与当前时间并使该用户注销?

如果你想找到 activity,你可以使用下面的 javascript 然后重定向到注销页面以清除会话。在这里我放了 5 秒的 inactivity

    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)
        
    }

我认为这可能有帮助: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