Internet, Networking, & Security Web Development How to Use PHP to Force a File Download The content-disposition header overrides the browser's inline-display feature by Jennifer Kyrnin Freelance Contributor Jennifer Kyrnin is a professional web developer who assists others in learning web design, HTML, CSS, and XML. our editorial process LinkedIn Jennifer Kyrnin Updated on November 13, 2019 Tweet Share Email Web Development CSS & HTML Web Design SQL 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 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: <?phpheader("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. Was this page helpful? Thanks for letting us know! Get the Latest Tech News Delivered Every Day Email Address Sign up There was an error. Please try again. You're in! Thanks for signing up. There was an error. Please try again. Thank you for signing up. Tell us why! Other Not enough details Hard to understand Submit