How to Use PHP to Force a File Download

The content-disposition header overrides the browser's inline-display feature

Because most modern browsers display PDF and media files inline, use the PHP programming language — which allows you to change the HTTP headers of files that you’re writing — to force the browser to download rather than display a given file type.

You'll need PHP on the web server where your files will be hosted, a file to be downloaded, and the MIME type of the file in question.

How to Use PHP to Force a File to Download

Fibre optic broadband
John Lamb / Getty Images

This process requires two separate steps. First, you'll create a PHP file that governs the file you wish to protect, and then you'll add a reference to that PHP file within the HTML of the page in which it appears.

After you upload a file to the server, create a PHP document in a text editor. If, for example, you wish to force sample.pdf to download instead of to display inline, create a script like this:

<?php
header("Content-disposition: attachment; filename=sample.pdf");
header("Content-type: application/pdf");
readfile("sample.pdf");
?>

The content-type reference in the PHP is important — it's the MIME type of the file you're protecting. If, for example, you saved an MP3 file instead, you'd need to replace application/pdf with audio/mpeg.

There should be no spaces or carriage returns anywhere in the file (except after a semi-colon). Blank lines will cause PHP to default to the MIME type of text/html and your file won't download.

Save the PHP file to the same location as your HTML pages. Then modify the page's link to the PDF as follows:

<a href="sample.php">Download the PDF</a>

Considerations

Two important considerations govern this procedure. First, if someone discovered the direct link to the PDF file, he or she can access it directly without the PHP getting in the way. Second, you'll need PHP protection for each file you wish to protect using this quick-and-easy approach. To protect several files in this manner, it makes sense to name the protected file and the PHP file with the same name, differing only in the extension, to keep everything straight.

Format
mla apa chicago
Your Citation
Kyrnin, Jennifer. "How to Use PHP to Force a File Download." ThoughtCo, May. 14, 2021, thoughtco.com/using-php-to-force-download-3469180. Kyrnin, Jennifer. (2021, May 14). How to Use PHP to Force a File Download. Retrieved from https://www.thoughtco.com/using-php-to-force-download-3469180 Kyrnin, Jennifer. "How to Use PHP to Force a File Download." ThoughtCo. https://www.thoughtco.com/using-php-to-force-download-3469180 (accessed March 28, 2024).