What are the best practices for handling user activity and online status in PHP applications to ensure accurate tracking?
To accurately track user activity and online status in PHP applications, it is essential to update the user's last activity timestamp regularly and handle user status changes effectively. One common approach is to update the timestamp whenever a user performs an action on the site and regularly check for inactive users to update their status.
// Update user's last activity timestamp
$user_id = $_SESSION['user_id'];
$query = "UPDATE users SET last_activity = NOW() WHERE id = $user_id";
mysqli_query($connection, $query);
// Check for inactive users and update their status
$inactive_threshold = 300; // 5 minutes of inactivity
$query = "UPDATE users SET status = 'offline' WHERE last_activity < (NOW() - INTERVAL $inactive_threshold SECOND)";
mysqli_query($connection, $query);