Sometimes you struggle with issues that seem to be small at first glance but still consume a lot of time to find out what the real problem is especially when the issue can only be reproduced when a specific browser or version is used. In my case I build a script to download a PDF file in PHP. It seemed to work in all browsers until a client uploaded a very specific PDF file that wouldn’t open in chrome’s buildin PDF viewer but worked in all other browsers and also offline. Ahhhrr is it a chrome bug, or did I do something wrong? Continue reading to find out what I did to solve it.
My PHP file responsible for downloading the pdf file looked like this:
1 2 3 4 5 6 7 8 |
protected function download($spec) { header('Content-Type: '.$spec['mime_type']); header('Content-Transfer-Encoding: Binary'); header('Content-disposition: attachment; filename="'.basename($spec['source']).'"'); readfile($spec['source']); } |
The problem is the readfile part. That doesn’t do a really good job for larger/some PDF files. I don’t know exactly what goes wrong, maybe when I have time I will try to figure that out but for now I will just present you a solution that worked for me:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
protected function download($spec) { header('Content-Type: '.$spec['mime_type']); header('Content-Transfer-Encoding: Binary'); header('Content-disposition: attachment; filename="'.basename($spec['source']).'"'); $fp = fopen($spec['source'], "r") ; ob_clean(); flush(); while (!feof($fp)) { $buff = fread($fp, 1024); print $buff; } exit; } |
Now the PDF download is working again for me in Chrome, and all other browsers. At least until I find another exceptional case were it doesn’t ;-).
More info:
- https://stackoverflow.com/questions/5670785/chrome-has-failed-to-load-pdf-document-error-message-on-inline-pdfs
What is $spec[‘source’]? What is “r”? I can’t puzzle together what is going here.