Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP + PDF, how to save a downloaded PDF using curl?

Welcome

I have a little problem with saving the downloaded pdf on the page. To download pdf I use Curl:

$CurlConnect = curl_init();
curl_setopt($CurlConnect, CURLOPT_URL, 'http://website.com/invoices/download/1');
curl_setopt($CurlConnect, CURLOPT_POST,   1);
curl_setopt($CurlConnect, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($CurlConnect, CURLOPT_POSTFIELDS, $request);
curl_setopt($CurlConnect, CURLOPT_USERPWD, $login.':'.$password);
$Result = curl_exec($CurlConnect);

Now in $Result(string) i have all PDF file content. And now begins my problem. I would like to save the downloaded pdf:

header('Cache-Control: public'); 
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="new.pdf"');
header('Content-Length: '.filesize($Result));
readfile($Result);

Unfortunately, when I save or open a new PDF file, I get a blank document. Perhaps the problem is with the last lines of:

header('Content-Length: '.filesize($Result));
readfile($Result);

Unfortunately, I do not know what to change them to make it work ... I ask for your help. Thanks

like image 865
Kuba Avatar asked Apr 09 '13 08:04

Kuba


2 Answers

Both filesize and readfile accepts files as arguments. You are providing a string instead of a file.

Please try this.

$CurlConnect = curl_init();
curl_setopt($CurlConnect, CURLOPT_URL, 'http://website.com/invoices/download/1');
curl_setopt($CurlConnect, CURLOPT_POST,   1);
curl_setopt($CurlConnect, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($CurlConnect, CURLOPT_POSTFIELDS, $request);
curl_setopt($CurlConnect, CURLOPT_USERPWD, $login.':'.$password);
$Result = curl_exec($CurlConnect);

header('Cache-Control: public'); 
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="new.pdf"');
header('Content-Length: '.strlen($Result));
echo $Result;
like image 188
Quicksilver Avatar answered Nov 19 '22 17:11

Quicksilver


Maybe that:

// ...
$Result = curl_exec($CurlConnect);
$file = 'file.pdf';
$fileName = 'fileName.pdf';
file_put_contents($file, $Result);

and than:

header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');

readfile($file);

I hope I helped!

like image 21
mkjasinski Avatar answered Nov 19 '22 16:11

mkjasinski