How can timestamps be effectively used in PHP sessions to manage user logouts and session expiration?

To manage user logouts and session expiration in PHP sessions, timestamps can be used to track when the session was last accessed. By comparing the current time with the last access time, you can determine if the session has expired and log the user out accordingly.

// Start the session
session_start();

// Set the session timeout period (in seconds)
$session_timeout = 1800; // 30 minutes

// Check if session variable last_activity is set
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > $session_timeout)) {
    // Session expired, destroy session and log user out
    session_unset();
    session_destroy();
    header("Location: logout.php");
    exit();
}

// Update last activity timestamp
$_SESSION['last_activity'] = time();