By setting the Content-type to Application/octet-stream, you can download the dynamically generated content as a file and believe that everyone will. Then use Content-disposition to set the download file name, this also has a lot of people know. Basically, the download program is written like this:
Copy Code code as follows:
$filename = "Document.txt";
Header (' Content-type:application/octet-stream ');
Header (' Content-disposition:attachment filename= '. $filename);
print "hello!";
?>
However, if the $filename is UTF-8 encoded, some browsers will not work properly. For example, to change the above program slightly:
Copy Code code as follows:
$filename = "Chinese filename. txt";
Header (' Content-type:application/octet-stream ');
Header (' Content-disposition:attachment filename= '. $filename);
print "hello!";
?>
the header of the output actually looks like this:
Content-disposition:attachment; Filename= Chinese filename txt In fact, according to the definition of RFC2231, multi-language encoded
content-disposition should be so defined:
Content-disposition:attachment; filename*= "UTF8 '%e4%b8%ad%e6%96%87%20%e6%96%87%e4%bb%b6%e5%90%8d.txt" namely:
Add * Before the equals sign in filename
filename values are divided into three paragraphs in single quotes, which are character sets (UTF8), language (empty), and UrlEncode file names.
• It is best to add double quotes, otherwise the part of the filename will not appear in Firefox
• Note that the results of UrlEncode and PHP UrlEncode function results are not the same, PHP UrlEncode will replace the space into a +, and here need to substitute for%20
After testing, it was found that several major browsers support the following:
IE6
attachment; Filename= ""
FF3
attachment; Filename= "UTF-8 filename"
attachment; filename*= "UTF8 '"
O9
attachment; Filename= "UTF-8 filename"
Safari3 (Win)
doesn't seem to support it? None of the above methods.
In this way, the program has to write to support all major browsers:
Copy Code code as follows:
$ua = $_server["Http_user_agent"];
$filename = "Chinese filename. txt";
$encoded _filename = UrlEncode ($filename);
$encoded _filename = str_replace ("+", "%20", $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. '"');
}
print ' ABC ';
?>