How can session variables be used to control access to specific pages for logged-in users in PHP?

Session variables can be used to control access to specific pages for logged-in users in PHP by setting a session variable upon successful login and checking for the existence of that variable on restricted pages. If the session variable is not set, the user can be redirected to a login page or denied access to the restricted page.

// Start the session
session_start();

// Check if the user is logged in by verifying the session variable
if(!isset($_SESSION['logged_in'])) {
    // Redirect the user to the login page
    header("Location: login.php");
    exit;
}

// Restricted page content here