views:

158

answers:

2

Hi all, I want a php page to 'display' a pdf. Here is the code:

<?php
  header("Content-type: application/pdf");
  readfile('Reportage - Berlin.pdf');  //tried echo(readfile(...)) as well
?>

Not very complicated I think, but somehow firefox cant detect that this is a pdf. This works in Safari but in firefox, i get a prompt to download the file, so i get like a pdftest.php file. I know im getting my file because if I rename the extension to pdf, i can open it.

This seems too simple! am i missing something?

+5  A: 

If you want it to open in the browser using Adobe Reader then that can also depend on the browser setting. The reason why it's saying the filename is pdftest.php is because you're not telling the browser what the filename is.

If you want to force the browser to download it, add this:

header('Content-Disposition: attachment; filename="downloaded.pdf"');

Htbaa
+1 Or just putting the filename as a trailing path part after the `pdftest.php` works as well. (This can be necessary for non-ASCII filenames.)
bobince
@Htbaa : what if i do not want to force a download? adding this forces safari to download the file instead of 'previewing' it in the browser window. i guess a bigger question: is this browser preview is more of a safari-only feature? is there a way to simulate this behaviour in ff? however this definitely answers my question of how to make ff see the type.
Ying
@bobince : Exactly what I needed! You are the man(or woman)!
Ying
@Ying: You can use `Content-Disposition: inline; filename...` to allow the browser to attempt to display it inline. However, in-browser PDF requires a plugin, and letting Adobe Reader or Foxit install their PDF plugins is a very, very bad idea for security. It leaves machines open to exploitation of vulnerabilities in the PDF reader from any web page or frame (this has been the number one source of web infections over the last year).
bobince
@bobince: thanks will definitely keep that in mind. how would you explain to the marketing team that we cant have a flashy preview because of browser security? :D
Ying
Heh. As the webapp author, you just make sure it works both with and without a plugin loaded (ie. don't use an embedded `<object>` for PDF) and I guess you let someone else worry about the client-side security once the half the machines in the office are plagued with keyloggers and ReallyGoodFakeAntiVirus 2010. :-)
bobince
+2  A: 

Htbaa is right about what line you should add, but since Ying asks for the browser not to download the file, the correct line would be:

header('Content-Disposition: inline; filename="downloaded.pdf"');

and by the way, you don't want to echo(readfile(...)), since it would add an int representing the size of the file read (php.net/readfile)

1ace
and of course, as a header is *has* to be put *before* you start printing the content of the file
1ace