How can the code be optimized to prevent users from accessing restricted pages after logging out?

To prevent users from accessing restricted pages after logging out, you can check if the user is logged in before allowing access to those pages. This can be done by setting a session variable upon login and checking for its presence on restricted pages. If the session variable is not set, the user should be redirected to the login page.

<?php
session_start();

if(!isset($_SESSION['logged_in'])) {
    header("Location: login.php");
    exit();
}

// Restricted page content here
?>