How can an expiration time be implemented to track user activity and online status accurately in PHP?

To accurately track user activity and online status in PHP, an expiration time can be implemented by storing a timestamp in the database or session when the user last accessed the site. By comparing this timestamp with the current time, we can determine if the user is still active or has gone offline.

// Set expiration time in seconds (e.g. 5 minutes)
$expiration_time = 300;

// Update user's last activity timestamp in the database or session
$_SESSION['last_activity'] = time();

// Check if user is still active based on expiration time
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity']) > $expiration_time) {
    // User has gone offline
    // Perform actions like updating online status to offline
} else {
    // User is still active
    // Perform actions like updating online status to online
}