Entry
How can I force a link to result in the user downloading a file?
Aug 28th, 2000 07:00
Jonathan Haase, Christian Schmidt, Nathan Wallace, Rasmus Lerdorf
If you just want to force a download use the header() function to set
the Content-type to be application/octet-stream.
http://www.php.net/manual/function.header.php3
Internet Explorer's MIME-type support is broken, so it does not react to
the above. However, if you in addition use the Content-Disposition
header you can also force MSIE 5 to download the file.
This header also allows you to specify a filename. This works in both
Netscape and MSIE 5.
header("Content-Disposition: attachment; filename=\"myfile.abc\"");
One item of note is that IE 5 will not download the file if the
filetype is html or text. IE will display the file in the browser
rather than bringing up the file-save-as dialog.
I have found a way to "force" IE to bring up the file-save-as dialog.
It seems that the problem with the above example is that IE
uses "sniffing" to determine the mime type if you specify octet-
stream. Even if you use the Content-Disposition header. However
Microsoft did put in a way to disallow this "sniffing". If you specify
a mime type which is not immediately recognized, but which appears to
be valid then IE will accept this mime-type without sniffing and handle
the Content-Disposition header properly. In my code I specified
header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=\"myfile.abc\"");
This correctly forced IE to download the file instead of displaying it
and still functions correctly in Netscape.