When downloading files, many of my friends convert their Chinese names to English or full numbers before downloading them. next I will introduce how to directly download files using Chinese file names without garbled characters.
When downloading files, many of my friends convert their Chinese names to English or full numbers before downloading them. next I will introduce how to directly download files using Chinese file names without garbled characters, the code is as follows:
- $ Filename = "Chinese file name .txt ";
- Header ('content-Type: application/octet-stream ');
- Header ('content-Disposition: attachment; filename = '. $ filename );
- Print "Hello! ";
- ?>
Save the program into UTF-8 encoding and then access, IE6 download file name will be garbled, FF3 download file name only "Chinese" two words, Opera 9 everything is normal, the output header is actually like this:
Content-Disposition: attachment; filename = Chinese file name .txt
In fact, according to the RFC2231 definition, the multi-language encoding Content-Disposition should be defined as follows:
Content-Disposition: attachment; filename * = "attachment"
That is, add * before the equal sign after filename. The filename value is divided into three sections by single quotation marks, which are character set (utf8), Language (null), and URL code file names. it is best to add double quotation marks, otherwise, the part after the space in the file name cannot be displayed in Firefox.
Note: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.
The instance code is as follows:
- $ File = "/tmp/Chinese name .tar.gz ";
- $ Filename = basename ($ file );
- Header ("Content-type: application/octet-stream ");
- // Process the Chinese file name
- $ Ua = $ _ SERVER ["HTTP_USER_AGENT"];
- $ Encoded_filename = urlencode ($ filename );
- $ Encoded_filename = str_replace ("+", "% 20", $ encoded_filename );
- 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 .'"');
- }
- Header ('content-Disposition: attachment; filename = "'. $ filename .'"');
- Header ("Content-Length:". filesize ($ file ));
- Readfile ($ file );
- ?>
In this way, we have completely solved the problem of garbled Chinese characters.