Is there a way I can piggy back sessions to know if the user is online?
I.e: use logs on, I set a $_SESSION variable, user times out- cookie Garbage collector update
You can also use the onunload
tag... On the body
More information here (https://www.w3schools.com/jsref/event_onunload.asp)
This way you don't have to wait 4 -5 minutes for the user to get offline.
But you should still use the ajax update method in-case the user's browser crashes...
Edit:
As @Quentin pointed out in the comments you may not be able to send out requests but there is a way you can do it...
Explained in more detail in this Article.
So basically they are using the sendBeacon()
Here is an Example
window.addEventListener("unload", function logData() {
navigator.sendBeacon("/log", analyticsData);
});
NOTE: Although it should be kept in mind that this should not be the only method you should depend upon, and should implement for redundancy...
It sounds like your "is the person online" comparison logic isn't taking into account the timezones. If you are dealing with timezones in this manner, I strongly recommend that you store all your times in GMT, and convert them to local time for your users right before you display them. This will make any comparison operations very simple.
There's a nice SO thread about timezones here.
The solution that I have implemented for this is to, on every page load by an authenticated user, set/reset a memcache var such as "user_{userid}isonline" => true and expire it in 5 minutes. Then check if the var is in the cache when I access the user's info. Depending on the size of your user base, if you want to get a list of everyone online, you could use a memcache getmulti call with an array of "user{userid}_isonline" keys for all of your users.
of course, this really depends on how often a user will change pages on your site... to get a more accurate representation of the users online, you could implement an ajax xmlhttprequest call on your page running at a small interval (30 seconds or so) that resets the memcache var, and have the memcache var expire in less time (1 minute to account for possible browser issues). This is not COMPLETELY accurate, but as http does not have a persistent connection to the server, you are pretty limited on what you can do.
IF you require an up to the second representation of who is online, you could maybe have a flash app loaded in your page that connects to a jabber server, then just check if that particular user is logged in on the server.
Store the time-zone in the table, and use it in a calculation to find that users local time in comparison to the local time of the user viewing the page.
Edit:
Better yet, store all times as the server time, and base all calculations relative only to the server time.