Skip to content
PHP Logo

How can the PHP code be optimized to only display necessary online users without lagging?

To optimize the PHP code to only display necessary online users without lagging, we can implement a caching mechanism to store the list of online users and update it periodically. By retrieving the list from the cache instead of querying the database each time, we can reduce the processing time and prevent lagging.

php
// Check if the list of online users is cached
$onlineUsers = apc_fetch('online_users');

// If not cached or cache is expired, fetch from database and cache it
if (!$onlineUsers) {
    $onlineUsers = fetchOnlineUsersFromDatabase();
    apc_store('online_users', $onlineUsers, 60); // Cache for 60 seconds
}

// Display the list of online users
foreach ($onlineUsers as $user) {
    echo $user['username'] . "<br>";
}