How does .htaccess interact with PHP scripts for user authentication?

When using .htaccess for user authentication in PHP scripts, you can protect your files or directories by requiring users to enter a username and password before accessing them. To interact with PHP scripts, you can use PHP's built-in authentication functions to validate user credentials provided by the .htaccess file.

<?php
$username = 'admin';
$password = 'password';

if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) || $_SERVER['PHP_AUTH_USER'] != $username || $_SERVER['PHP_AUTH_PW'] != $password) {
    header('WWW-Authenticate: Basic realm="Restricted Area"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Access Denied';
    exit;
}

// Your protected content here
?>