Download htaccess protected files using PHP and CURL Download htaccess protected files using PHP and CURL curl curl

Download htaccess protected files using PHP and CURL


here is the working code, you made a mistake on the line with : curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);

$username = "MyUsername";$password = "MyPassword";$url = "http://www.example.com/private/file.pdf";$ch = curl_init();curl_setopt($ch, CURLOPT_URL, $url);curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);$output = curl_exec($ch);$info = curl_getinfo($ch);curl_close($ch);header("Content-Type: application/octet-stream");header("Content-Disposition: attachment; filename=file.pdf");echo ($output);


There is a CURLOPT_BINARYTRANSFER option that seems missing. The output you pasted is $info not $output btw. It shows the download happened, download_content_length is 27369.


If you're trying to download a file, you should use CURLOPT_FILE instead of doing a RETURNTRANSFER = true. That'll write the downloaded data out to a file on your system directly, without flood PHP's memory space. Remember, PHP generally runs with a memory limit, and you can easily exceed it by downloading a large file.

Using RETURNTRANSFER is only useful if you're going to be doing in-memory processing of the transferred data, such as loading HTML into the DOM system for parsing.

Try this instead:

$ch = curl_init();curl_setopt($ch, CURLOPT_URL, $url);curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);curl_setopt($ch, CURLOPT_FILE, "/name/of/file/to/write/to/on/your/machine");$output = curl_exec($ch);$info = curl_getinfo($ch);curl_close($ch);