How can PHP developers optimize the code to display the total number of online users at the bottom of a webpage in a forum setting?

To display the total number of online users at the bottom of a webpage in a forum setting, PHP developers can use sessions to track user activity. Each time a user logs in or accesses a page, their session is updated. By counting the active sessions, the total number of online users can be displayed dynamically on the webpage.

<?php
// Start the session
session_start();

// Update user's last activity time in session
$_SESSION['last_activity'] = time();

// Count active sessions to get total online users
$active_users = 0;
foreach ($_SESSION as $key => $value) {
    if (time() - $value < 300) { // consider user active if last activity within 5 minutes
        $active_users++;
    }
}

// Display total online users at the bottom of the webpage
echo "Total online users: " . $active_users;
?>