The Linux Page

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
From: download@example.com
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.