I tried to download files in a htaccess protected directory using php and curl. This is my code:
$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_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
But this code does nothing... how can I initiate the download of file.pdf?
Thank you!
Also, if I echo $output, i get this:
Array ( [url] => http://www.example.com/private/file.pdf [content_type] => application/pdf [http_code] => 200 [header_size] => 264 [request_size] => 116 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 0.007898 [namelookup_time] => 0.006777 [connect_time] => 0.006858 [pretransfer_time] => 0.006922 [size_upload] => 0 [size_download] => 27369 [speed_download] => 3465307 [speed_upload] => 0 [download_content_length] => 27369 [upload_content_length] => 0 [starttransfer_time] => 0.007839 [redirect_time] => 0 )
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With