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]);
}
}
?>
Keywords
Related Questions
- How can PHP be used to compare the contents of an original gallery folder with its thumbnail folder to ensure they stay in sync?
- What are the potential consequences of using session_register() function in PHP, and what is the recommended alternative?
- What is the significance of using the foreach loop with key-value pairs in PHP form validation?