我们已经知道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();
我想实现对当前代码的修改,并执行以下操作:
答案 0 :(得分:1)
按使用时间跟踪,而不是当前时间/已存储时间。只需用它们来计算剩余的时间。这是一个简单的例子。可能会出现一些小错误和改进。它应该足以帮助您实施解决方案。
用户访问页面:
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)