Currently Browsing: Home » Force Download Dialog Boxes

Force Download Dialog Boxes

When we browse the web, we click on links. That’s what makes the web a web – the links between pages. Sometimes, those links lead us not to pages, but to files. Many types of files pop up dialog boxes prompting downloads – executables, videos, etc.

However, certain filetypes, thanks to modern web browsers, are rendered as an in-browser page, such as images, PDFs, and MP3s. While this may be a convenience, at times we may wish to force the user to download the files, not just view them in their browser.

In this article I will show two easy ways to do this. The first is using .htaccess, and the second is using PHP.


In your .htaccess file, add the following line for each extension you wish to force download:

AddType application/octet-stream extension

For example, if I wanted to force PDFs and MP3s to download, I would do this:

AddType application/octet-stream .pdf
AddType application/octet-stream .mp3

It’s really quite simple, and can be done quickly.


The PHP version is a bit more complicated, but can be useful if you want to have a bit more control. For example, you can use download IDs instead of the filename to prevent direct hotlinking. For example, you can assign the ID “3148″ to “BusinessPlan.pdf” and do a forced download.

The basic code looks like this:

header('Content-Disposition: attachment; filename="'.$file.'"');

Of course, this is a huge security hole if you use the structure download.php?file=BusinessPlan.pdf, as anyone can access any file on your webserver. Thus, steps should be taken to secure the user input, or use a database of IDs.

Of course, if you’re just forcing download and don’t need extra control over the download process, you should use the .htaccess version, as it is much simpler and easier to use.

This entry was posted on Thursday, February 4th, 2010 at 05:00:12. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

2 Responses to “Force Download Dialog Boxes”

  1. Richie says:

    I did the .htaccess thing. It worked on my dev machine on chrome, FF and safari. A day later, I uploaded to a test box for the client to see cause it was prelaunch and it stopped working on both my dev box and test machine. Strange thing is, I didn’t change any code at all. I’m baffled and spending way too much time trying to force a download with htaccess.

    • T3RR0R says:

      Strangely enough I am experiencing a similar situation… however, I used this instead…

      ForceType application/octet-stream
      Header set Content-Disposition attachment

      and after about 2-3 hrs without changing anything it stopped working

Leave a Reply

Want to be notified when someone replies? Subscribe to this post's comment RSS feed.
Any field marked with a * is required.