How can PHP be used to create a password-protected area on a website?

To create a password-protected area on a website using PHP, you can use sessions to store the user's login status. When a user enters the correct password, set a session variable to indicate that they are logged in. On each protected page, check if the session variable is set to allow access. If not, redirect the user to the login page.

<?php
session_start();

$correct_password = "password123";

if(isset($_POST['password'])) {
    if($_POST['password'] == $correct_password) {
        $_SESSION['loggedin'] = true;
    }
}

if(!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
    header("Location: login.php");
    exit;
}
?>