2014年8月1日 星期五

php 使用 header 下載檔案開頭多一個空白

我是個 php 菜鳥,最近常有朋友跟我抱怨,用 php 寫檔案下載的時候,下載回來的檔案都會損毀,如果是文字檔的話開頭會多個空白,我感到非常困惑。他們有一個共通點,用的方法都是透過 header 進行檔案下載。

然後我就股溝到了 stackoverflow 的這篇「using the browser prompt to download a file」,Anne 在回答中詳細了說明每個 header 參數的作用,完整 code 如下:

<?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;
}
?>

我發現朋友們與 Anne 的 code 不同的地方主要就是 ob_clean() 和 flush(),叫他們加了這兩行後就好惹,Anne 針對這兩行的說明是“Make sure the headers are send to the browser before the download starts”,我實在看得不是很懂。經朋友測試表示,只要 ob_clean() 就可以解決問題了,想深入研究的話可以參考 「why ob_clean and flush ?」。

1 則留言: