How can .htpasswd be used to implement a login window for a PHP website?

To implement a login window for a PHP website using .htpasswd, you can create a .htpasswd file with encrypted username and password pairs. Then, use PHP to prompt users for their credentials and validate them against the .htpasswd file. If the credentials match, grant access to the protected content.

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = $_POST['username'];
    $password = $_POST['password'];
    
    $htpasswd_file = '.htpasswd';
    $htpasswd_contents = file_get_contents($htpasswd_file);
    
    $htpasswd_lines = explode("\n", $htpasswd_contents);
    
    foreach ($htpasswd_lines as $line) {
        list($stored_username, $stored_password) = explode(':', $line);
        
        if ($username == $stored_username && password_verify($password, $stored_password)) {
            // Successful login
            echo 'Welcome, ' . $username . '!';
            exit;
        }
    }
    
    // Invalid credentials
    echo 'Invalid username or password.';
}
?>
<form method="post">
    <input type="text" name="username" placeholder="Username" required><br>
    <input type="password" name="password" placeholder="Password" required><br>
    <button type="submit">Login</button>
</form>