Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download htaccess protected files using PHP and CURL

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 )
like image 858
nmarti Avatar asked Feb 09 '11 11:02

nmarti


2 Answers

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);
like image 138
classics40 Avatar answered Nov 15 '22 01:11

classics40


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.

like image 26
chx Avatar answered Nov 15 '22 01:11

chx