How can you redirect a user to a logout page after their session times out in PHP?

When a user's session times out in PHP, you can redirect them to a logout page by checking if the session is still active on each page load. If the session has expired, you can redirect the user to the logout page using header() function.

// Check if the session is still active
session_start();

if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > 1800)) {
    // If session has expired, redirect to logout page
    header("Location: logout.php");
    exit;
}

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