How can PHP detect inactivity and update user status accordingly?

To detect inactivity in PHP and update user status accordingly, you can set a timestamp in the user's session when they log in. Then, periodically check if the difference between the current time and the timestamp exceeds a certain threshold to determine if the user is inactive. If the user is inactive, update their status accordingly in the database.

// Set timestamp in user's session when they log in
$_SESSION['last_activity'] = time();

// Check for inactivity and update user status
$inactive_threshold = 300; // 5 minutes of inactivity
if (time() - $_SESSION['last_activity'] > $inactive_threshold) {
    // Update user status in the database
    $user_id = $_SESSION['user_id'];
    // Perform database query to update user status
}