Bhavin Nattar Bhavin Nattar - 3 months ago 14
PHP Question

PDF files do not display properly in browser

We are trying to display a

PDF File
from Live Server (PHP Verion 5.2) which is not getting displayed properly... instead of file
is getting displayed..

Same file is getting displayed if we are trying to display from Local Server(PHP Version 5.4)..

We have tried following to display PDF from Server (Which displays ByteCode):

header("Content-type: application/pdf");
header("Content-Length: " . filesize($url_path)); // '$url_path' variable is fullpath to PDF file
readfile($url_path) or die("File not found ");

Output ByteCode:

%PDF-1.5 2 0 obj << >> endobj 3 0 obj << /Type /Page /Parent 1 0 R /MediaBox [0 0 598 834] /Contents 4 0 R /Resources << /XObject << /img0 5 0 R >> /ProcSet [ /PDF /Text /ImageC] /Font 2 0 R >> /Annots 6 0 R >> endobj 4 0 obj << /Filter /FlateDecode /Length 61 >> stream x

If we try to display using below line then it works fine..

echo "<script type='text/javascript'> window.location.href = '".$url_path."'; </script>";

We already tried changing .htaccess code as below:

(1) RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^(.+).pdf$ /cgi-bin/pdf.php?file=$1 [L,NC,QSA]

(2) RewriteEngine On
RewriteCond %{REQUEST_URI} \.(pdf)$ [NC]
RewriteRule ^ /viewpdf.php?request_url=%{REQUEST_URI} [L]

Still not working..


Finally got the solution:

While declaring header we should take care that no echo or print_r should be declared before it..

And if we import file in require(..) or include(..) or require_once(..) also should not contain any echo statement.. otherwise all header declaration after that will be ignored..

In short: above the header statement no echo statement should be written otherwise all header declaration will be ignored..