Clicking "Back" button from a page showing a PDF in Firefox and Chrome causes header to appear in the <body> tag
I'm running into a very strange error in Firefox and Chrome. The error doesn't occur in Safari. I'm displaying a PDF on a page with the following code (works fine):
header('Content-Length: ' . filesize($pdfPath));
header('Content-Type: application/pdf');
header('Content-Transfer-Encoding: binary');
header('Content-Disposition: inline; filename="' . $pdfId . '.pdf"');
readfile($pdfPath);
The PDF loads up beautifully, but when I click the back button in the browser (Firefox and Chrome), the page that I jump back to has the HTTP header included in the body tag.
HTTP/1.1 200 OK Date: Tue, 08 Mar 2011 00:18:47 GMT Server: Apache/2.0.63 (Unix) 开发者_StackOverflow中文版PHP/5.2.13 DAV/2 mod_ssl/2.0.63 OpenSSL/0.9.7l X-Powered-By: PHP/5.2.13 Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma: no-cache Content-Length: 7010 Keep-Alive: timeout=15, max=92 Connection: Keep-Alive Content-Type: text/html
This header is for the current page (not the page that displayed the PDF). In debugging, I printed out the body tag with the following jQuery code:
console.log($('body').html());
The header appears before any other content in the body. Any ideas as to what could be causing this rogue header to appear?
Finally figured out what was going on, and the fix was quite simple. I just added an exit() after the readfile(), so the final code ended up looking like this:
header('Content-Length: ' . filesize($pdfPath));
header('Content-Type: application/pdf');
header('Content-Transfer-Encoding: binary');
header('Content-Disposition: inline; filename="' . $pdfId . '.pdf"');
readfile($pdfPath);
exit();
精彩评论