当前位置: 动力学知识库 > 问答 > 编程问答 >

php and mysql session destroyed before update

问题描述:

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.

//On page load with a logged-in user
mysql_query("UPDATE `users`
             SET `last_activity` = '" . time() . "' 
             WHERE `username` = '" . mysql_real_escape_string($_SESSION['username']) . "'");

note that assumes you've added an INT column to your table named last_activity

and then in a process that executes, say, every 15 minutes:

mysql_query("UPDATE `users` 
             SET `online` = 0 
             WHERE `last_activity` < '" . strtotime('-30 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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: