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.

Difficulty: Hard
Time Required: 10 minutes
Here’s How:
  1. Upload the file you want to make available for download to your Web server. For example,


  2. Edit a new PHP file – I recommend naming it the same name as your downloaded file, only with the extension .php. For example:


  3. Open the PHP block:


  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:


  7. Then close the PHP block and save the file:


  8. Your PHP file should look like this:

    header(‘Content-disposition: attachment; filename=huge_document.pdf’);
    header(‘Content-type: application/pdf’);

  9. Link to your PHP file as a download link. For example:

    <a href=”huge_document.php”>Download my huge document (PDF)</a>

  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
By dbglory Posted in PHP

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s