By setting Content-Type to application/octet-stream, you can download the dynamically generated content as an object. You can use content-disposition to set the downloaded file name. Basically, download programs are written like this:
<?php
$filename = "document.txt";
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $filename);
print "Hello!";
?>
After the browser is opened, you can download document.txt.
However, if $ filename is UTF-8 encoded, Some browsers won't be able to handle it. For example, change the above program slightly:
<? PHP
$ Filename = "Chinese file name .txt ";
Header ('content-type: Application/octet-stream ');
Header ('content-Disposition: attachment; filename = '. $ filename );
Print "Hello! ";
?>
Save the program as a UTF-8 code and then access, IE6 download file name will be garbled. The file name downloaded under ff3 is only in Chinese. Everything works normally in opera 9.
The output header is actually like this:
Content-Disposition: attachment; filename = Chinese file name .txt
In fact, according to rfc2231, the content-Disposition of multi-language encoding should be defined as follows:
Content-Disposition: attachment; filename*="utf8''%E4%B8%AD%E6%96%87%20%E6%96%87%E4%BB%B6%E5%90%8D.txt"
That is:
- Add the equal sign after filename *
- The filename value is divided into three sections by single quotes, which are character set (utf8), language (null), and URL code file names.
- It is best to add double quotation marks. Otherwise, the content after the space in the file name cannot be displayed in Firefox.
- Note that the urlencode result is not the same as the urlencode function result of PHP. The urlencode of PHP will replace the space with +, and replace it with % 20 here.
After experiments, we found that the support for several mainstream browsers is as follows:
<? PHP
$ UA = $ _ server ["http_user_agent"];
$ Filename = "Chinese file name .txt ";
$ Encoded_filename = urlencode ($ filename );
$ Encoded_filename = str_replace ("+", "", $ encoded_filename );
Header ('content-type: Application/octet-stream ');
If (preg_match ("/MSIE/", $ UA )){
Header ('content-Disposition: attachment; filename = "'. $ encoded_filename .'"');
} Else if (preg_match ("/Firefox/", $ UA )){
Header ('content-Disposition: attachment; filename * = "utf8/'. $ filename .'"');
} Else {
Header ('content-Disposition: attachment; filename = "'. $ filename .'"');
}
?>
Pay attention to the sentence in the Red Line. Most websites say "+" should be replaced with "20%", but I find it is incorrect after trying it. I need to replace "+" ""
I tested IE6, IE8, and ff3.5.3 normally.