How can timestamps be effectively used in PHP to track user activity and online status?

To track user activity and online status in PHP, timestamps can be effectively used by updating a user's last activity timestamp in the database whenever they perform an action on the website. By comparing the current timestamp with the last activity timestamp, you can determine if the user is online or inactive. This can help in managing user sessions and displaying online/offline status indicators.

// Update user's last activity timestamp in the database
$user_id = 1; // Example user ID
$current_timestamp = time();
$update_query = "UPDATE users SET last_activity = $current_timestamp WHERE id = $user_id";
// Execute the update query

// Check if user is online based on last activity timestamp
$inactive_threshold = 300; // 5 minutes of inactivity
if ($current_timestamp - $last_activity_timestamp < $inactive_threshold) {
    echo "User is online";
} else {
    echo "User is offline";
}