Syndicate content

Force the download of any file

How to force a download of any file in a CGI script

I have been wondering for a while, now I have the answer, so I can share it with you guys.

Your script has to do the following steps:

  1. Print a header which at least includes:

    1. Content-Type: application/force-download

      (you can also use octet-stream instead of force-download)

    2. Content-Disposition: attachement; filename="<name of your file>"

      (don't put the < and > around your filename! but keep the double quotes)

      Other header information can be included. It is very strongly suggested that you put the Content-Length: to the size of the file to be downloaded. In a shell script under Linux you can use the following syntax:

      echo "Content-Length: `stat -c %s $filename`"

      If the file is likely to change often, then put some cache control information:

      Cache-Control: no-cache

      The rest is up to you.

  2. Terminate the header with an empty line
  3. Send the file (in a shell script, this is simply: cat $filename)
  4. You're done! (Well, I guess you tested what you just wrote already...)


Problems with secure servers... for Internet Explorer you need special cache control considerations and that in the right order. Fun, hey? The following is what I use for my company's Apache setup:

Content-Location: $filename
Content-Type: application/octet-stream
Content-Disposition: attachment; filename="$filename"
Content-Transfer-Encoding: binary
Content-Length: $filesize
Pragma: private
Cache-Control: private, must-revalidate
Title: $filename
Expires: Thu, 1 Jan 1970 00:00:00 GMT

<binary or text file data follows here>

Note that the double quotes around the "$filename" in the content disposition are optional. We strongly suggest you use them if anyone may one day use a space in the filename. Otherwise it won't work.

For a complete list of valid MIME types, look at the IANA website: MIME Media Types.

Syndicate content

Diverse Realty

Diverse Realty Team

Want a New Home?
Want to Sell Your House?

Call Alex at
+1 (916)
220 6482

Alexis Wilke, Realtor
Lic. # 02024063

Cory Marcus, Broker
Lic. # 01079165


Terms of Site Index

Find the page/content you are looking for with our index.

  • Breezy
  • RedHat

    RedHat is a Linux distribution. There was a free version before that has now be renamed Fedora (first FedoraCore). RedHat still offers Server Class Linux distributions. Note that Linus Torvalis is working for RedHat.

  • audio
    Sound emitted by your computer is in general called "the audio."
  • index
  • path