2012-06-29 45 views
0

我在文件下載問題時遇到了問題。在Chrome中,下載工作正常。在Firefox中,它產生的文件,如年底一些HTML標題:如何編寫適合文件下載的PHP腳本?

<!DOCTYPE .....> 
... 
... 

對於一些其他的瀏覽器,下載的文件會錯過一些行了。我該如何編寫腳本才能使它在許多瀏覽器中正常工作?這是我現在的代碼:

private function downloadRawFileHelper($file) { 
    if (ini_get('zlib.output_compression')) { 
     ini_set('zlib.output_compression', 'Off'); 
    } 
    if (!file_exists($file)) { 
     die('File Not Found'); 
    } 

    header("Pragma: public"); 
    header("Expires: 0"); 
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
    header("Cache-Control: private", false); 
    header("Content-Type: text/php"); 
    header("Content-Disposition: attachment; filename=\"". basename($file). "\""); 
    header("Content-Transfer-Encoding: binary"); 
    header("Content-Length: " . filesize($file)); 
    ob_clean(); 
    flush(); 
    readfile($file); 
    $this->view = 'fileedit'; 
} 
+0

您應該開始意識到這與任何特定的Web瀏覽器無關。 – Lion

回答

1

儘量readfile後把一個exit,我認爲這將解決您的問題

0

我找不到任何代碼問題。你可以在你的函數結尾添加exit()die()。將其更改爲:

private function downloadRawFileHelper($file) { 
    if (ini_get('zlib.output_compression')) { 
     ini_set('zlib.output_compression', 'Off'); 
    } 
    if (!file_exists($file)) { 
     die('File Not Found'); 
    } 

    header("Pragma: public"); 
    header("Expires: 0"); 
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
    header("Cache-Control: private", false); 
    header("Content-Type: text/php"); 
    header("Content-Disposition: attachment; filename=\"". basename($file). "\""); 
    header("Content-Transfer-Encoding: binary"); 
    header("Content-Length: " . filesize($file)); 
    ob_clean(); 
    flush(); 
    readfile($file); 
    $this->view = 'fileedit'; 
    exit(); 
} 

您正在將文件輸出到瀏覽器。所以你需要在這之後停止腳本執行。

希望這有助於:)

0

flush()之前添加ob_end_clean();readfile()exit()。另外,您可能會考慮使用X-SendFile而不是純PHP來將文件發送到客戶端,因爲這會在大文件的情況下佔用寶貴的資源。

0

這裏是你的問題:

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

試舉一個名稱爲您的檔案館,例如:

header("Content-Disposition: attachment; filename=\"". basename($file). "filename.extension\""); 
0

調試HTTP問題的最好辦法就是實際檢查是HTTP消息發送。今天的瀏覽器使這非常簡單。

如果該網站是公開的,您可以嘗試redbot.org來檢查響應。

最後,您正在Cache-Control中發送大量未定義和/或無用的響應頭字段,如「Content-Transfer-Encoding」或「check」指令。