如何在会话过期后自动更新数据库而不刷新我的页面 [英] How to update the database automatically after session is expired without refreshing on my page

查看:41
本文介绍了如何在会话过期后自动更新数据库而不刷新我的页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码需要刷新或单击页面,然后才能转到索引页面,并且在会话过期后更新数据库之前.

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.

如何在会话过期后自动更新数据库,以便在不刷新或点击页面的情况下活动用户为 0?

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?

$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();
}

推荐答案

我建议在这里使用不同的方法.您不应更新数据库中的活动"字段.否则,您在数据库中创建lastActivity"字段并在每次用户在网站上执行某些操作时更新它.

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.

在这种情况下,您可以通过如下查询数据库轻松检测哪些用户处于非活动状态:

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

您的 PHP 代码如下所示:

Your PHP code will look like:

$online = "UPDATE users SET lastActive = NOW() WHERE username = '".$_SESSION['username']."'";
mysqli_query($con, $online);  

这篇关于如何在会话过期后自动更新数据库而不刷新我的页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆