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

To track user activity and determine online status in PHP, timestamps can be effectively used by updating a user's timestamp in the database each time they perform an action on the website. By comparing the current time with the user's last activity timestamp, you can determine if they are currently online or when they were last active.

// Update user's timestamp in the database
$user_id = 1;
$current_time = time();

// Update the user's last activity timestamp
$query = "UPDATE users SET last_activity = $current_time WHERE id = $user_id";
// Execute the query

// Check if the user is currently online
$online_threshold = 300; // 5 minutes
$last_activity = // Get user's last activity timestamp from the database

if ($current_time - $last_activity <= $online_threshold) {
    echo "User is currently online";
} else {
    echo "User was last active at: " . date('Y-m-d H:i:s', $last_activity);
}