Wednesday, June 20, 2012

How To Use PHP to Force a File Download

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.

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 - 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:
    ?>[/blockquote>
  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:

  1. There should be no spaces or carriage returns anywhere in the file. Blank lines will cause PHP to default to text/html and your file won't download.

What You Need

  • The file to be downloaded
  • The MIME type of the file

1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete