How can developers implement a more scalable and flexible password protection system in PHP without resorting to separate password scripts for each page?

Developers can implement a more scalable and flexible password protection system in PHP by creating a reusable function that can be included on any page requiring password protection. This function should handle password verification and redirect users if they are not authenticated. By centralizing the password protection logic in one function, developers can easily manage and update the system without duplicating code across multiple pages.

<?php

function protectPage() {
    session_start();
    
    if (!isset($_SESSION['authenticated']) || $_SESSION['authenticated'] !== true) {
        header('Location: login.php');
        exit;
    }
}

protectPage();

?>