简体   繁体   English

在浏览器上更新数据库关闭

[英]Update database on browser close

I have a website I'm creating and I want to be able to see who is online and who is not. 我有一个正在创建的网站,我希望能够看到谁在线和谁不在。 Seeing who is online is not hard, when you log in, "online" field in database changes from 0 to 1. But the problem is with going offline. 看到谁在线并不难,当您登录时,数据库中的“在线”字段从0更改为1。但是问题在于离线。 I managed to do that IF the person logs out on the log out button and gets redirected to logout.php page: 如果该人在注销按钮上注销并重定向到logout.php页面,则可以做到这一点:

<?php
session_start();
$user_check=$_SESSION['login_user'];

if(session_destroy())
{
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("masterrad", $connection);

$query2 = mysql_query("update users set online = '0' where username = '$user_check'", $connection);

header("Location: index.php");
}
?>

But if he just closes the page nothing will change in the database since he never went to the logout.php page. 但是,如果他只是关闭页面,因为他从未访问过logout.php页面,因此数据库中的内容将保持不变。

So I was wondering if there is a better way to do this? 所以我想知道是否有更好的方法来做到这一点?

On each page that you consider to be an 'online' page. 在您认为是“在线”页面的每个页面上。
You could use @Alec Deitloffs idea of a 'last_time_spotted' field and update the online flag based on that and your time period. 您可以使用@Alec Deitloffs关于“ last_time_spotted”字段的想法,并根据该时间和您的时间段来更新在线标记。 No cron needed. 不需要cron。

$query2 = mysql_query("update users set `online` = '0' where `online` = '1' AND (`last_time_spotted` < NOW() - INTERVAL 15 MINUTE), $connection);

The way that most sites perform this, I believe, is by having a "last time spotted" field in the database. 我相信,大多数站点执行此操作的方式是在数据库中具有“最后一次发现”字段。 Every time the user goes to a new page, that field is updated for them to the current time. 每次用户进入新页面时,该字段将被更新为当前时间。 A cron job would execute every 10, 15 minutes (whatever you want), and if the current time minus the time the user was last spotted is greater than the threshold you want (ie, inactive for seven minutes), then you would consider them offline. Cron作业将每10、15分钟(无论您要执行什么操作)执行一次,并且如果当前时间减去最后一次发现用户的时间大于您想要的阈值(即,不活动7分钟),则您将考虑使用它们离线。

It's very, very difficult to actually have code execute completely and successfully when a user leaves the page, closes the browser, et cetera. 当用户离开页面,关闭浏览器等时,要使代码完全且成功地执行实际上是非常非常困难的。 Unfortunately, this means that alternative methods need to be taken, and it's my understanding that this is the most popular choice. 不幸的是,这意味着需要采用其他方法,据我了解,这是最受欢迎的选择。 Or at least, one of the simpler ones to implement. 或者至少是较简单的一种实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM