How can PHP be used to manage and update online user lists effectively, especially in scenarios where users may frequently refresh or navigate away from the page?

To manage and update online user lists effectively in scenarios where users may frequently refresh or navigate away from the page, we can use PHP sessions to keep track of active users. By storing user information in a session variable, we can easily update the user list whenever a user visits or leaves the page.

<?php
session_start();

// Add user to online list
if (!isset($_SESSION['online_users'])) {
    $_SESSION['online_users'] = [];
}

$user_id = // get user id here
$_SESSION['online_users'][$user_id] = time();

// Update user list by removing inactive users
$timeout = 300; // 5 minutes timeout
foreach ($_SESSION['online_users'] as $user_id => $last_activity) {
    if (time() - $last_activity > $timeout) {
        unset($_SESSION['online_users'][$user_id]);
    }
}
?>