How can session timeouts be effectively utilized to manage user online status in PHP?

Session timeouts can be effectively utilized to manage user online status in PHP by setting a session variable with a timestamp when the user logs in, and then checking this timestamp against the current time on each page load. If the time difference exceeds a certain threshold, the user can be considered offline.

// Start session
session_start();

// Set session variable with timestamp when user logs in
$_SESSION['last_active'] = time();

// Check if user is online based on session timeout
$timeout = 300; // 5 minutes
if (isset($_SESSION['last_active']) && (time() - $_SESSION['last_active']) > $timeout) {
    // User is considered offline
    // Perform necessary actions (e.g. update user status in database)
}