PHP下載檔案名稱亂碼問題詳解_PHP教程

來源:互聯網
上載者:User
通過把Content-Type設定為application/octet-stream,可以把動態產生的內容當作檔案來下載,相信這個大家都會。那麼用Content-Disposition設定下載的檔案名稱,這個也有不少人知道吧。基本上,下載程式都是這麼寫的:

 
header('Content-Disposition: attachment; filename=' . $filename);print "Hello!";?> 

這樣用瀏覽器開啟之後,就可以下載document.txt。

但是,如果$filename是UTF-8編碼的,有些瀏覽器就無法正常處理了。比如把上面那個程式稍稍改一下:

 
header('Content-Disposition: attachment; filename=' . $filename);print "Hello!";?>  

把程式儲存成UTF-8編碼再訪問,IE6下載的檔案名稱就會亂碼。 FF3下下載的檔案名稱就只有“中文”兩個字。Opera 9下一切正常。

輸出的header實際上是這樣子:

Content-Disposition: attachment; filename=中文 檔案名稱.txt
其實按照RFC2231的定義,多語言編碼的Content-Disposition應該這麼定義:

Content-Disposition: attachment; filename*="utf8''%E4%B8%AD%E6%96%87%20%E6%96%87%E4%BB%B6%E5%90%8D.txt"

即:

filename後面的等號之前要加 * filename的值用單引號分成三段,分別是字元集(utf8)、語言(空)和urlencode過的檔案名稱。 最好加上雙引號,否則檔案名稱中空格後面的部分在Firefox中顯示不出來 注意urlencode的結果與php的urlencode函數結果不太相同,php的urlencode會把空格替換成+,而這裡需要替換成%20

經過實驗,發現幾種主流瀏覽器的支援情況如下:

IE6 attachment; filename=""

FF3 attachment; filename="UTF-8檔案名稱"

attachment; filename*="utf8''"

O9 attachment; filename="UTF-8檔案名稱"

Safari3(Win) 貌似不支援?上述方法都不行

這樣看來,程式必須得這樣寫才能支援所有主流瀏覽器:

  
$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';?>


http://www.bkjia.com/PHPjc/446657.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/446657.htmlTechArticle通過把Content-Type設定為application/octet-stream,可以把動態產生的內容當作檔案來下載,相信這個大家都會。那麼用Content-Disposition設定下載的文...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.