Skip to content
PHP Logo

How can you effectively manage user sessions in PHP to determine if a specific user is online?

To effectively manage user sessions in PHP to determine if a specific user is online, you can use session variables to track when a user logs in and logs out. By setting a specific session variable when a user logs in and unsetting it when they log out, you can check for the presence of this variable to determine if the user is online.

php
// Start the session
session_start();

// Set a session variable when the user logs in
$_SESSION['is_online'] = true;

// Check if the user is online
if(isset($_SESSION['is_online'])) {
    echo 'User is online';
} else {
    echo 'User is offline';
}

// Unset the session variable when the user logs out
unset($_SESSION['is_online']);