Nick Thomas Nick Thomas - 3 months ago 10
PHP Question

Using PHP CURL to display PDF file is just producing strange text

I'm using PHP CURL to access PDF files, and everything is working properly with the exception of the end result being unreadable. My code is as follows:

$cookie = 'cookies.txt';
$timeout = 30;
$url = "http://www.somesite.com/sample_report.pdf";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout );
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Encoding: none','Content-Type: application/pdf'));

$result = curl_exec($ch);
echo $result;


When I just manually enter the URL into the browser, the PDF properly displays. But when using CURL, it displays pages of gibberish text.

Looking at the code view in the browser, I see a lot of lines like these:

5 0 obj
<</Length 6 0 R/Filter /FlateDecode>>
stream


And on the page where the .pdf should display, is the following code:

<body>
<p>
<object id='mypdf' type='application/pdf' width='100%' height='90%' data='sample_report.pdf'>
</object>
</p>
</body>


Does anyone have any suggestions?

Answer

Try it with this (keep your first 3 lines the same)

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 10); 
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout );
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Encoding: none','Content-Type: application/pdf')); 

header('Content-type: application/pdf');
$result = curl_exec($ch);
curl_close($ch);
echo $result;

The line I commented out doesn't appear to be doing anything. I added the "header" line. If I take that line out, I get a page of gibberish as you do. If it is still saying "headers already sent", there must be something setting a header elsewhere.

EDIT:

I would also suggest changing this:

<object id='mypdf' type='application/pdf' width='100%' height='90%' data='sample_report.pdf'></object>

To this:

<iframe src="sample_report.pdf" width="100%" height="90%"></iframe>

Or, if your PHP script is called sample_report.pdf (for instance) try changing iframe src to sample_report.php.

Comments