What are common methods for creating a password-protected area in PHP websites?

To create a password-protected area in PHP websites, one common method is to use HTTP authentication. This involves prompting users to enter a username and password before accessing the protected area. Another method is to store usernames and passwords in a database and validate user credentials against the database before granting access. Additionally, you can use sessions to keep track of authenticated users throughout their visit to the website.

<?php
// Start the session
session_start();

// Check if the user is not authenticated
if (!isset($_SESSION['authenticated']) || $_SESSION['authenticated'] !== true) {
    // Check if the user has submitted a username and password
    if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
        // Validate the username and password (this is a basic example, should be improved for production use)
        if ($_SERVER['PHP_AUTH_USER'] === 'admin' && $_SERVER['PHP_AUTH_PW'] === 'password') {
            $_SESSION['authenticated'] = true;
        } else {
            // Invalid credentials, show an error message
            header('WWW-Authenticate: Basic realm="Restricted Area"');
            header('HTTP/1.0 401 Unauthorized');
            echo 'Access Denied';
            exit;
        }
    } else {
        // Prompt the user to enter their credentials
        header('WWW-Authenticate: Basic realm="Restricted Area"');
        header('HTTP/1.0 401 Unauthorized');
        echo 'Please enter your username and password';
        exit;
    }
}

// The user is authenticated, display the protected content
echo 'Welcome to the protected area!';
?>