How can PHP sessions be used to restrict access to certain pages until a user is logged in?

To restrict access to certain pages until a user is logged in, PHP sessions can be used to track the user's login status. When a user successfully logs in, a session variable can be set to indicate that the user is authenticated. On restricted pages, this session variable can be checked, and if the user is not logged in, they can be redirected to a login page.

<?php
session_start();

// Check if user is not logged in, redirect to login page
if(!isset($_SESSION['loggedin'])) {
    header("Location: login.php");
    exit();
}
?>