How can PHP be used to handle authentication before downloading a file from a remote server?

To handle authentication before downloading a file from a remote server using PHP, you can send an HTTP request with the necessary authentication credentials to the server. Once authenticated, the server will respond with the file content, which can then be saved locally.

<?php
$remoteFileUrl = 'https://example.com/file.pdf';
$username = 'your_username';
$password = 'your_password';

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

$fileContent = curl_exec($ch);

file_put_contents('local_file.pdf', $fileContent);

curl_close($ch);
?>