将时间存储在数据库中,并在 PHP 中登录后恢复


Store time in DB and resume after log in PHP

我们已经知道,PHP 中的以下代码将在用户处于非活动状态 5 分钟后注销。

$timeout = 5*60; // Set timeout minutes
$logout_redirect_url = "index.php"; // Set logout URL
if (isset($_SESSION['start_time'])) {
    $elapsed_time = time() - $_SESSION['start_time'];
    if ($elapsed_time >= $timeout) {
        session_unset();
        session_destroy();
        header("Location: $logout_redirect_url");
    }
}
$_SESSION['start_time'] = time();

我想实现对当前代码的修改并执行以下操作:

    假设
  • 用户在自动注销前还剩 3 分钟时注销(假设时间在他不活动 2 分钟后没有重新开始),我们通过将时间存储在数据库中来跟踪他离开的时间 (MySQL) 中,然后从他重新登录后的 3 分钟开始减少。我该怎么做?

按使用的时间跟踪,而不是按当前时间/存储时间跟踪。只需使用这些来计算剩余时间。这是一个快速示例。可能会有一些小错误和改进。它应该足以帮助您实施解决方案。

用户访问页面:

if (empty($_SESSION['start_time'])) {
  $_SESSION['start-time'] = time();
}
$timeLeft = //get time from db
//if there is a value in the db, that is the time left, otherwise, use the max time allowed (new timer)
$timeLeft = (!empty($timeLeft)) ? $timeLeft : $timeAllowed
$timePassed = time() - $_SESSION['start_time'];
if ($timePassed > $timeAllowed) {
  //logout
}

然后,当用户离开时:

$timeLeft = $timeAllowed - (time() - $_SESSION['start_time']);
//Store $timeLeft in the database - should be a value like 180 (3 minutes)