How to open a PDF files in web browser using PHP?

PHP uses a standard code to display the pdf file in web browser. The process of displaying pdf involves location of the PDF file on the server and it uses various types of headers to define content composition in form of type, Disposition, Transfer-Encoding etc. PHP passes the PDF files to read it on the browser. Browser either shows it or download it from localhost server then display pdf.

Note: PHP is not actually reading the PDF file. It does not recognize File as pdf. It only passes the PDF file to the browser to be read there. If copy the pdf file inside htdocs folder of XAMPP then it does not need to specify the file path.

Example 1: This example display the pdf file on the browser.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Store the file name into variable
$file = 'filename.pdf';
$filename = 'filename.pdf';
  
// Header content type
header('Content-type: application/pdf');
  
header('Content-Disposition: inline; filename="' . $filename . '"');
  
header('Content-Transfer-Encoding: binary');
  
header('Accept-Ranges: bytes');
  
// Read the file
@readfile($file);
  
?>

chevron_right


Output:

Example 2:
this examples displays a format and explains every section of code

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// The location of the PDF file
// on the server
$filename = "/path/to/the/file.pdf";
  
// Header content type
header("Content-type: application/pdf");
  
header("Content-Length: " . filesize($filename));
  
// Send the file to the browser.
readfile($filename);
?> 

chevron_right


Output:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.