How can PHP sessions be effectively managed to prevent unauthorized access to certain pages?

To prevent unauthorized access to certain pages in PHP, sessions can be effectively managed by implementing a login system where users are required to log in with valid credentials. Once a user is authenticated, a session variable can be set to track their logged-in status. On pages that require authorization, this session variable can be checked to ensure only authenticated users can access them.

<?php
session_start();

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

// Restricted page content here
?>