Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
27
rated 0 times [  28] [ 1]  / answers: 1 / hits: 46931  / 15 Years ago, sat, june 27, 2009, 12:00:00

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 updates the database to update their status as offline.



EDIT: I want a solution that does not involve times or dates. I want something to ride on sessions or something similar. Guessing if someone is online is not good enough for what I need.


More From » php

 Answers
3

Don't bother with figuring out the differences between time zones—that's not necessary.


Whenever the user accesses a page, set/update a lastActiveTime field in their record of the Users table. Then, do a COUNT for all users having a lastActiveTime within the last 5 minutes. Anything more than this, and they can be considered "offline."


If you use your server-time, via the NOW() function in MySQL, you'll avoid the need to deal with time zones. This is the standard way of tracking how many users are presently online (meaning, active within the last x minutes).


Constantly Updated


If you would like to know they are still active (even when they're not jumping from page to page), you could include a bit of JavaScript to ping your server every 60 seconds. It'll work the same way as my original suggestion, but it will update your records without requiring users to be frantically browsing your site at least once every five minutes.


Original 2009 Code


var stillAlive = setInterval(function () {
/* XHR back to server
Example uses jQuery */
$.get("stillAlive.php");
}, 60000);

Updated 2022 Code


We can use fetch and promises today to more precisely issue these calls. Fetch will replace our earlier XHR approach using jQuery. Fetch returns a Promise, which we'll use (via the await keyword) to defer timing of our next call. Once the call to stillAlive.php is complete, and a response has been retrieved, we'll setup the next ping for 60 seconds later.


(async function ping () {
// Asynchronously call stillAlive.php
await fetch( "stillAlive.php" );
// Issue this call again in 60 seconds
setTimeout( ping, 60_000 );
}());

[#99230] Tuesday, June 23, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sabinal

Total Points: 144
Total Questions: 112
Total Answers: 107

Location: Ghana
Member since Mon, Aug 22, 2022
2 Years ago
;