【问题标题】:PHP Content-Disposition header: Specialcharacters in the filenamePHP Content-Disposition 标头:文件名中的特殊字符
【发布时间】:2016-11-06 15:26:24
【问题描述】:

我正在尝试使用 php 下载文件名中包含特殊字符的文件。 不幸的是,这些字符被“_”取代了。

代码:

$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();

返回一个名为

的文件
"__$%&_=_.txt"

我尝试了 urlencode()、rawurlencode()、mb_convert_string($filename, "UTF-8") 的不同变体。 已经存在的问题Special Characters in Content-Disposition filename、How to encode the filename parameter of Content-Disposition header in HTTP? 和PHP: RFC-2231 How to encode UTF-8 String as Content-Disposition filename 并没有真正帮助我。 你还有什么想法吗?

文件编码为 UTF-8。

Sprintf() 似乎不是问题:

header("Content-Disposition: attachment; filename*=utf-8''" . rawurlencode($filename)); 

或

header("Content-Disposition: attachment; filename=\"" . $filename . "\""); 

给出相同的结果。

【问题讨论】:

  • sprintf() 等不支持 unicode。他们将破坏多字节文本。 sprintf 也没有 mb_*() 等价物。您将不得不使用其他方式。
  • 感谢您的意见。但是, sprintf() 似乎不是问题。 header("Content-Disposition: attachment; filename*=utf-8''" . rawurlencode($filename));或 header("Content-Disposition: attachment; filename=\"" . $filename . "\"");给出相同的结果。文件名仍然是“_$%&_=.txt”。它还尝试了 mb_convert_encoding() 等的不同变体。
  • 在我找到更好的方法之前,似乎最方便的事情就是实际音译。

标签: php encoding http-headers


【解决方案1】:

你试过了吗?

header("Content-Disposition: attachment; filename=".utf8_decode(htmlspecialchars_decode($filename))); 

【讨论】:

    猜你喜欢
    • 2011-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-12
    • 2011-12-23
    • 2022-07-06
    • 2011-02-02
    相关资源
    最近更新 更多