You are here: Home / Topics / How to open a PDF file in browser with PHP

How to open a PDF file in browser with PHP

Filed under: PHP on 2023-07-02 21:05:19

PHP uses standard code to display the pdf file in the web browser. The process of viewing the PDF file involves locating the PDF file on the server. It uses various types of headers to define the composition of the content in the form of Type, Layout, Transfer-Encode, etc. PHP transmits the PDF files to be able to read them on the browser. The browser displays it or downloads it from the localhost server, then displays the pdf.
 

Example 1 : How to open a PDF file in browser with PHP


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

 

Example 2 : How to open a PDF file in browser with PHP
 

<?php 
 // The file path
 $file = "/path/to/file.pdf"; 
   
 // Header Content Type
 header("Content-type: application/pdf"); 
   
 header("Content-Length: " . filesize($file)); 
   
 // Send the file to the browser.
 readfile($file); 
?>

About Author:
Y
Yatendra Sir     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.