so im trying to have a table that shows which users are online on my site I have everything working besides the part where if someone closes the site without logging out first they stay on the table as logged in. i’ll try to eplain my situation the best I can.
in my database I have a users table in that table is online when you login your online status is set to 1, when you click logout online is set to 0. here is the code im trying to use so that if someone is inactive for 10minutes they will be logged out ( online set to 0 )
<?php
session_start();
$timeout = 10; // Set timeout minutes
$logout_redirect_url = "logout.php"; // Set logout URL
$timeout = $timeout * 60; // Converts minutes to seconds
if (isset($_SESSION['last_activity'])) {
$elapsed_time = time() - $_SESSION['last_activity'];
if ($elapsed_time >= $timeout) {
mysql_query("UPDATE users SET online = 0 WHERE username = '".$_SESSION['username']."'")
or die(mysql_error());
session_destroy();
header("Location: $logout_redirect_url");
}
}
$_SESSION['last_activity'] = time();
?>
This works fine it logs them out if they wait the 10minutes, but if they just close the browser it keeps online = 1 which displays them on the list.
I believe the problem is that when they close the browser that destroys the session before it gets the chance to update the users online and set it to 0
is there anyway around this? help would be very much appreciated thanks 🙂
btw I know not to use mysql anymore and everything, I will try to switch to something else once I learn more and get everything working first.
The underlying problem is that when a user closes their browser, there’s no reliable way to first communicate with your server. [There are things you could try, but in my opinion that’s a rabbit hole you shouldn’t go down] All you really “know” is how recently the user visited your site logged-in. (in your case
$_SESSION['last_activity']).At a basic level, you will want to start persisting that information in your database, and then have a process kicked off occasionally to cleanup stale sessions.
e.g.
note that assumes you’ve added an
INTcolumn to your table namedlast_activityand then in a process that executes, say, every 15 minutes:
Unix servers have something called cron especially for period tasks/scripts, so that’s what I would recommend for kicking off your cleanup script.