- $ Filename = "document.txt ";
- Header ('content-Type: application/octet-stream ');
- Header ('content-Disposition: attachment; filename = '. $ filename );
- Print "Hello! ";
- ?>
After a browser is opened, you can download document.txt.
However, if $ filename is UTF-8 encoded, some browsers won't be able to handle it.
Example:
- $ 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.
Output header: Content-Disposition: attachment; filename = Chinese file name .txt
In fact, according to the RFC2231 definition, the Content-Disposition of multi-language encoding should be defined as follows: Content-Disposition: attachment; filename * = "identifier" that is: before the equal sign after filename, add the * filename value and use single quotation marks to divide it into three sections, namely 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 replaces the space with +, and the urlencode must be replaced with % 20 here.
After experiments, we found that the support for several mainstream browsers is as follows:
- $ Filename = "Chinese file name .txt ";
- $ Encoded_filename = urlencode ($ filename );
- $ Encoded_filename = str_replace ("+", "% 20", $ encoded_filename );
- $ Ua = $ _ SERVER ["HTTP_USER_AGENT"];
- Header ('content-Type: application/octet-stream ');
- If (preg_match ("/MSIE/", $ ua) {// bbs.it-home.org
- 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 ';
- ?>
|