[PHP]撰寫PHP下載檔案後,下載的檔案會產生錯誤..

用 php 寫檔案下載的時候,下載回來的檔案都會損毀,如果是文字檔的話開頭會多個空白。
最主要的原因就是:UTF-8的BOM字元產生的檔頭錯誤。解決方法就是使用ob_clean()+flush();如下:

<?php
$file = 'monkey.gif';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    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;
}
?>

檔案輸出前使用ob_clean()+flush();清除UTF-8的BOM字元

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *