I've created a very simple multiuser game for learning purposes.
As users log on, each other user gets an update of all currently logged in users.
When a user logs in, it simply sets a value for that user in the SQL database to 1. When they're logged out, the value should be 0.
I'm using $(window).unload(function() {}); to try to catch tab/browser closes, but it only sortof works.
Two questions:
Is there a better way to catch browser or tab close?
In the event that it misses the tab close, or their machine crashes, or internet connection dies, or the user simply walks away from the machine, I want to go ahead and log them out automatically.
I'm using an HTML/Jquery frontend with PHP backend. What can I do to accomplish the second question? I assume I need to do it in PHP.. we're working under the assumption that the browser is likely no longer even around, hence not processing jquery stuff. Can PHP do something on an continuous timer that checks to see if the user is still around... without simply having the users click a button every 10 seconds?
Edit: There's a potential solution here: How to detect if a user has logged out, in php? But I'm using ajax to avoid page refreshes. Ideally, the user will never f5 the page, or click any buttons (I'm testing, remember, this is not a for real app). Will PHP see last activity without a full page refresh?
Edit2: I've added the following code to my PHP, with a corresponding jquery function using setInterval
if (isset ($_POST['keepalive'])) {
if (filter_input(INPUT_POST,'keepalive') == '1') {
$name = $_SESSION['name'];
$time = time();
mysql_query("UPDATE tictac_names SET keep_alive = '$time' WHERE name ='$name'") or die(mysql_error());
}
}
This plugs a unix epoc timestamp into my table, which will be super easy for simple calculations.
My question now is: How do I tell PHP to run a check for each logged in user ever X number of seconds? My PHP backend file is primarily just set to catch post variables and run code, then hand it back to jquery. Since this code is intended to log out inactive browsers/users, I can't rely on jquery sending a request to PHP, and there's no refresh of the PHP. Do I need to do some kind of cron job or some bizarreness to get PHP to check for all users who have not updated in the last X seconds?
Help!