1. Computing

Discuss in my forum

How To Use PHP to Force a File Download

Get Browsers to Download a File They Would Normally Open Inline

By

Web browsers are amazing programming feats. They are tools that we use everyday and most people don’t appreciate how useful they are. One thing that browsers do behind the scenes is try to make all your clicks do something. This means that more and more file types can be opened for viewing in web browsers.

Most of the time, this is a good thing, as it can be very frustrating to click on a link to a document you want to read, and then have to wait for it to download and finally open on your computer, only to discover that you don’t have the right program to open it. In fact, these days that rarely happens.

But what if you have a file you want people to download? If it is an HTML file or a PDF, you can’t just post link, as the web browsers open those automatically. instead you need to do some trickery using PHP.

PHP allows you to change the HTTP headers of files that you’re writing, so that you can force a file to be downloaded that normally the browser would load in the same window. This is perfect for files like PDFs, document files, images, and video that you want your customers to download rather than read online.

Difficulty: Hard

Time Required: 10 minutes

What You Need:

Here’s How:

  1. Upload the file you want to make available for download to your web server. For example,
    huge_document.pdf
  2. Edit a new PHP file in your web editor—I recommend naming it the same name as your downloaded file, only with the extension .php. For example:
    huge_document.php
  3. Open the PHP block:
    <?php
  4. On the next line, set the HTTP header:
    header("Content-disposition: attachment; filename=huge_document.pdf");
  5. Then set the MIME-type of the file:
    header("Content-type: application/pdf");
  6. Point to the file you want to download:
    readfile("huge_document.pdf");
  7. Then close the PHP block and save the file:
    ?>
  8. Your PHP file should look like this:
    <?php
    header("Content-disposition: attachment; filename=huge_document.pdf");
    header("Content-type: application/pdf");
    readfile("huge_document.pdf");
    ?>
  9. Link to your PHP file as a download link. For example:
    <a href="huge_document.php">Download my huge document (PDF)</a>

Tips:

  • 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 text/html and your file won’t download.
  1. About.com
  2. Computing
  3. Web Design / HTML
  4. Web Programming
  5. PHP
  6. How To Use PHP to Force a File Download

©2014 About.com. All rights reserved.