How can PHP be used to track user activity and online status in a community website?

One way to track user activity and online status in a community website using PHP is by updating a timestamp in the database every time a user interacts with the site. By regularly updating this timestamp, you can determine if a user is currently active or offline based on their last activity time. Additionally, you can use this information to display online status indicators next to user profiles or in chat systems.

// Update user's last activity timestamp in the database
function updateLastActivity($userId) {
    $currentTime = time();
    // Update last_activity field in the users table for the user with $userId
    $query = "UPDATE users SET last_activity = $currentTime WHERE id = $userId";
    // Execute the query using your database connection
}

// Check if a user is currently online based on their last activity timestamp
function isUserOnline($userId, $timeout = 300) { // 300 seconds (5 minutes) timeout
    $currentTime = time();
    // Retrieve last_activity field from the users table for the user with $userId
    $query = "SELECT last_activity FROM users WHERE id = $userId";
    // Execute the query using your database connection
    $lastActivity = // Retrieve last_activity value from the database
    if ($lastActivity != null && ($currentTime - $lastActivity) <= $timeout) {
        return true; // User is online
    } else {
        return false; // User is offline
    }
}