How to solve the problem in PHP download file name

  • 2020-06-15 07:56:23
  • OfStack

By setting ES0en-ES1en to application/ octet-ES4en, you can download dynamically generated content as a file, which I'm sure everyone knows. So use ES5en-ES6en to set the filename to download, as many of you know. Basically, the download program reads:

$filename = "document.txt";
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $filename);
print "Hello!";
?>

However, if $filename is es11EN-8 encoded, some browsers won't handle it properly. For example, change the above program slightly by 1:

$filename = " Chinese   The file name .txt";
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $filename);
print "Hello!";
?>

The output header actually looks like this:
Content - Disposition: attachment; filename= Chinese filename.txt actually follows the definition of RFC2231.
Content - Disposition: attachment; filename * = "utf8 E6 AD B8 E4 '% % % % % 96% 87% 20% E6 E5 B6 BB E4 % % % % 96% 87% % 90%. 8 D txt" namely:
The & # 8226; filename is preceded by the equal sign by *
The & # 8226; The value of filename is divided into three single quotation marks, which are character set (utf8), language (null), and urlencode filename.
The & # 8226; Double quotation marks are best, otherwise the following Spaces in the file name will not show up in Firefox
The & # 8226; Note that the result of urlencode is not quite the same as the urlencode function of php. urlencode of php replaces the space with +, and here we need to replace it with %20
After testing, the support of several major browsers was found as follows:
IE6
attachment; filename=""
FF3
attachment; filename=" ES66en-8 file name"
attachment; filename*="utf8''"
O9
attachment; filename=" ES74en-8 file name"
Safari3(Win)
Doesn't seem to support it? None of the above works
So the program must be written to support all the major browsers:

$ua = $_SERVER["HTTP_USER_AGENT"];
$filename = " Chinese   The file name .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';
?>

Related articles: