How can timestamps be effectively compared to determine session expiration in PHP?

To determine session expiration in PHP, timestamps can be effectively compared by calculating the current time against the timestamp when the session was last active. If the time difference exceeds a certain threshold (e.g. 30 minutes), the session can be considered expired.

// Get the timestamp when the session was last active
$lastActiveTimestamp = $_SESSION['last_active'];

// Calculate the current time
$currentTimestamp = time();

// Calculate the time difference
$timeDifference = $currentTimestamp - $lastActiveTimestamp;

// Check if the session has expired (e.g. after 30 minutes)
if ($timeDifference > 1800) {
    // Session has expired, destroy the session
    session_destroy();
    // Redirect to login page or perform any other action
}