How can a PHP script display the number of online users, including registered users, similar to a forum setup?

To display the number of online users, including registered users, in a PHP script similar to a forum setup, you can use sessions to track when a user is online. Each time a user logs in, you can set a session variable to mark them as online. When a user logs out or their session expires, you can unset the session variable. By counting the number of active session variables, you can determine the number of online users.

// Start the session
session_start();

// Set user as online when logging in
$_SESSION['online'] = true;

// Unset user as online when logging out or session expires
unset($_SESSION['online']);

// Count the number of online users (registered and guests)
$online_users = 0;
foreach ($_SESSION as $key => $value) {
    if ($value == true) {
        $online_users++;
    }
}

echo "Number of online users: " . $online_users;