How can HTTP authentication be handled when loading files from a remote server in PHP?

When loading files from a remote server in PHP that requires HTTP authentication, you can handle it by passing the authentication credentials in the URL using the format http://username:password@server/path/to/file. However, this method is not secure as it exposes the credentials in the URL. A more secure way is to use cURL in PHP to set the authentication headers.

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

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $remoteFile);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");

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

echo $response;
?>