[PHP] IE 下載檔案無法辨識檔名與檔案類型

今天碰到網站利用IE下載檔案時發生無法辨識檔名與檔案類型

花了一點時間找問題來源,原來是IE讀 http header 讀到uft-8的編碼時會有問題

只好針對IE多寫一個判斷,讓程式偵測到瀏覽器為IE時把檔名轉碼

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
function dl_file( $file ){
    if ( file_exists($file) ) {
        $filename = basename($file);
    }

    // 若為IE瀏覽器則將檔名編碼轉換成Big5
    if ( strpos( $_SERVER['HTTP_USER_AGENT'], "MSIE" ) ) {
        $filename = iconv('utf-8', 'big5', $filename);
    }

    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.$filename);
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: '.filesize($file) );
    ob_clean();
    flush();
    readfile($file);
    exit;
} else {
    echo "Error: File not found.";
    return false;
}

IE啊IE,ˊ_>ˋ………

Licensed under CC BY-NC-SA 3.0 TW
comments powered by Disqus