php

How to open a PDF file in browser with PHP

In this tutorial, we are going to see how to open a PDF file in browser with PHP. 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); 
?>
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *