How can the functionality of redirecting a user to a logout page after a session timeout be efficiently implemented in PHP?

When a user's session times out, they should be redirected to a logout page to ensure their account remains secure. This can be achieved by checking the session expiration time against the current time on each page load, and if the session has expired, redirect the user to the logout page.

// Check session expiration time
if(isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > 1800)) {
    session_unset();
    session_destroy();
    header("Location: logout.php");
    exit;
}

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