What are the best practices for handling user status updates, such as changing from "online" to "offline" based on their activity in a PHP application?

When handling user status updates in a PHP application, one of the best practices is to regularly update the user's status based on their activity. This can be achieved by setting a timeout for the user's session and updating their status to "offline" if they have been inactive for a certain period of time. Additionally, you can use AJAX calls to periodically check the user's activity and update their status accordingly.

// Check user activity and update status
function updateStatus($userId) {
    // Check user's last activity time
    $lastActivityTime = // Retrieve user's last activity time from database
    
    // Set timeout period (e.g. 5 minutes)
    $timeout = 5 * 60; // 5 minutes in seconds
    
    // If user has been inactive for longer than the timeout period, update status to "offline"
    if (time() - $lastActivityTime > $timeout) {
        // Update user's status to "offline" in the database
    } else {
        // Update user's status to "online" in the database
    }
}

// Call the updateStatus function for a specific user
updateStatus($userId);