[英]How to update the database automatically after session is expired without refreshing on my page
This code you need to refresh or click the page before it will go to index page and before it will update the database after the session is expired. 此代码需要刷新或单击页面才能进入索引页面,然后在会话过期后更新数据库。
How can I make it automatically that after session is expired it will update the database so the user active will be 0 without refreshing or clicking on page? 如何在会话过期后自动更新数据库,以便用户激活为0而不刷新或点击页面?
$idletime = 3600; //after 1hr the user gets logged out
if (time() - $_SESSION['timestamp'] >= $idletime){
$online = "UPDATE users SET active = 0 WHERE username = '".$_SESSION['username']."'";
mysqli_query($con, $online);
session_destroy();
header("Location:index.php");
} else {
$_SESSION['timestamp'] = time();
}
Best option is to not use an active/not active flag in the database, but rather use something like a last_active
timestamp. 最好的选择是不在数据库中使用活动/非活动标志,而是使用类似last_active
时间戳的内容。 When the user accesses a page, update the timestamp to CURRENT_TIMESTAMP()
. 当用户访问页面时,将时间戳更新为CURRENT_TIMESTAMP()
。 And to determine whether the user is currently active, query for WHERE active_timestamp < TIMESTAMPADD(MINUTE, -60, CURRENT_TIMESTAMP())
要确定用户当前是否处于活动状态,请查询WHERE active_timestamp < TIMESTAMPADD(MINUTE, -60, CURRENT_TIMESTAMP())
Make sure you set active_timestamp
as a DATETIME
type in the table structure. 确保在表结构中将active_timestamp
设置为DATETIME
类型。 ( ALTER TABLE users ADD COLUMN active_timestamp datetime AFTER username'
) ( ALTER TABLE users ADD COLUMN active_timestamp datetime AFTER username'
)
The problem here is that your script looks to want to kick the user out when the session is idle. 这里的问题是你的脚本看起来想要在会话空闲时踢出用户。 For this, you should look at JavaScript, set a timer that counts down over 1 hour and if there is no activity, redirect the page. 为此,您应该查看JavaScript,设置一个倒计时超过1小时的计时器,如果没有活动,则重定向页面。
I'd suggest to use a different approach here. 我建议在这里使用不同的方法。 You should not update the 'active' field in the database. 您不应更新数据库中的“活动”字段。 Otherwise you create 'lastActivity' field in the DB and update it every time user do something on the site. 否则,您在数据库中创建“lastActivity”字段,并在每次用户在网站上执行某些操作时更新它。
In this case you can easily detect which users are inactive by querying the database like this: 在这种情况下,您可以通过查询数据库轻松检测哪些用户处于非活动状态,如下所示:
SELECT * FROM users WHERE lastActivity < TIMESTAMP(CURRENT_TIMESTAMP() - INTERVAL 1 HOUR);
Your PHP code will look like: 您的PHP代码如下所示:
$online = "UPDATE users SET lastActive = NOW() WHERE username = '".$_SESSION['username']."'";
mysqli_query($con, $online);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.