Whats the easiest way to determine if a user is online? (PHP/MYSQL)

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 );
}());

Leave a Comment