How can PHP developers ensure that users are properly logged out when they leave a website to prevent them from being displayed as "online" indefinitely?

To ensure that users are properly logged out when they leave a website, PHP developers can implement a session timeout mechanism. This involves setting a session expiration time and regularly checking if the user is still active on the site. If the user has been inactive for a certain period, their session can be destroyed, logging them out automatically.

// Set session expiration time to 30 minutes
session_start();
$session_timeout = 30 * 60; // 30 minutes in seconds

if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity']) > $session_timeout) {
    // Destroy session and log user out
    session_unset();
    session_destroy();
    header("Location: logout.php");
    exit();
}

// Update last activity time
$_SESSION['last_activity'] = time();