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

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

Posted by: admin July 12, 2020 Leave a comment

Questions:

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

How to&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;

Answer:

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!