I am trying to download a file with php that has special characters in the file name. Unfortunately these characters are substituted by "_".
The code:
$filename = trim('<>$%&/=?' . '.txt');
header($_SERVER["SERVER_PROTOCOL"] . " 200 OK");
header("Cache-Control: public");
header("Content-Type: application/text");
header("Content-Transfer-Encoding: Binary");
header('Content-Disposition: attachment; '
. sprintf('filename="%s"; ', urlencode($filename))
. sprintf("filename*=utf-8''%s", urlencode($filename)));
echo "file contents";
die();
returns a file named
"__$%&_=_.txt"
I have tried different variations with urlencode(), rawurlencode(), mb_convert_string($filename, "UTF-8"). The already present issues Special Characters in Content-Disposition filename , How to encode the filename parameter of Content-Disposition header in HTTP? and PHP: RFC-2231 How to encode UTF-8 String as Content-Disposition filename did not really help me. Do you have any further ideas?
Encoding of the file is UTF-8.
Sprintf() seems not to be the problem:
header("Content-Disposition: attachment; filename*=utf-8''" . rawurlencode($filename));
or
header("Content-Disposition: attachment; filename=\"" . $filename . "\"");
give the same result.
I believe, the issue has nothing to do with the encoding of the filename ( "Content-Disposition: attachment; filename*=utf-8''" . rawurlencode($filename)
option seems correct).
Some characters such as ?
, <
, >
are just not allowed in filenames on particular platforms and replaced with _
by a browser.
Also, you can have both filename
and filename*
params in Content-Disposition
header, using the former as a fallback for client that doesn't support extended filename*
param. It can be done seamlessly with content-disposition lib.
你试过这个吗?
header("Content-Disposition: attachment; filename=".utf8_decode(htmlspecialchars_decode($filename)));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.