Skip to main content

How to Force a PDF File to Be Opened in the Web Browser Instead of Being Downloaded in PHP

When you access a website, your web browser looks at various headers to decide how to handle the content. These headers define the type of content, how it should be displayed, and how it should be transferred. For example, if you try to download a PDF file, your browser will look for headers that tell it how to interpret the file.

If the headers are set properly, your browser will know to download the file instead of trying to open it in a tab. This is just one example of how these headers can be used to control how content is displayed on a website. By understanding how these headers work, you can better control how your website appears to users.

If you have a PDF file that you want to be downloaded when clicked instead of being opened in the browser, you can use the following code:

header('Content-type: application/pdf');  
header('Content-Disposition: inline; filename="myPDF.pdf"'); 
header('Content-Transfer-Encoding: binary'); 
header('Accept-Ranges: bytes'); 
@readfile('myPDF.pdf'); 
$filename = "/path/to/myPDF.pdf";   
header("Content-type: application/pdf");  
header("Content-Length: " . filesize($filename)); 
readfile($filename); 

By continuing to use the site, you agree to the use of cookies.