How can PHP scripts handle authorization requirements, such as those enforced by a .htaccess file, when accessing files via HTTP?

When accessing files via HTTP that have authorization requirements enforced by a .htaccess file, PHP scripts can handle this by sending the appropriate authorization headers with the HTTP request. This can be achieved by setting the 'Authorization' header in the PHP script with the required credentials before making the HTTP request to access the file.

<?php
$url = 'http://example.com/protected-file.txt';
$username = 'username';
$password = 'password';

$authorization = base64_encode($username . ':' . $password);
$headers = array(
    'Authorization: Basic ' . $authorization
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
curl_close($ch);

echo $response;
?>