How can PHP be used to access files with directory protection using htaccess?

When trying to access files with directory protection using htaccess, PHP can be used to authenticate users before granting access to the files. This can be achieved by checking the user's credentials against the htaccess password file and only allowing access if the user is authenticated.

<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
    header('WWW-Authenticate: Basic realm="Restricted Section"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Authorization Required.';
    exit;
} else {
    $username = $_SERVER['PHP_AUTH_USER'];
    $password = $_SERVER['PHP_AUTH_PW'];
    
    // Check if the username and password are valid
    if ($username == 'admin' && $password == 'password123') {
        // Grant access to the protected files
    } else {
        header('HTTP/1.0 401 Unauthorized');
        echo 'Invalid username or password.';
        exit;
    }
}
?>