我编写以下php代码,如果用户不在网页上,则在10秒后销毁会话,但它不能正常运行。它在10秒后正确地杀死会话,但它不更新数据库。要更新数据库,我必须刷新浏览器上的index.php页面,然后它更新数据库。我希望会话将在10秒后自动销毁,如果我关闭浏览器或不活动,并将更新数据库,无论我是否在浏览器上。我不想用刷新来更新数据库。
$inactive = 10;
// check to see if $_SESSION["timeout"] is set
if (isset($_SESSION["timeout"])) {
// calculate the session's "time to live"
$sessionTTL = time() - $_SESSION["timeout"];
if ($sessionTTL > $inactive) {
$new_status= 0;
$checkbox = "UPDATE online SET status=($new_status) WHERE id=1 ";
$stmt = $conn->prepare($checkbox);
// Now we execute the query passing an array toe execute();
$results = $stmt->execute(array($new_status));
// Extract the values from $result
$error = $stmt->errorInfo();
header("Location:logout.php");
unset($_SESSION['username1']);
}
}
你这样做是不可能的。会话绑定到单个用户,如果用户变为非活动状态,他不会打开任何php脚本,这可能导致绑定到他的会话的操作。
如果您想检测不活动,您必须在数据库中存储最后一个操作的时间戳,并将该值与当前时间进行比较。
UPDATE user SET status=1, last_action=UNIX_TIMESTAMP() WHERE id=?;
设置不活动字段,可以使用
UPDATE user SET status=0 WHERE UNIX_TIMESTAMP() - last_action > 10;