What is the recommended method to check if a user is online in PHP?
To check if a user is online in PHP, you can use a combination of session variables and timestamps. When a user logs in, set a session variable with the current timestamp. Then, periodically check the timestamp against the current time to determine if the user is still considered online based on a defined time threshold.
// Start the session
session_start();
// Set the user as online when they log in
$_SESSION['last_activity'] = time();
// Check if the user is still online based on a time threshold (e.g. 5 minutes)
$onlineThreshold = 300; // 5 minutes in seconds
if(isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity']) < $onlineThreshold) {
echo 'User is online';
} else {
echo 'User is offline';
}