2015-12-11 174 views
2

我試圖編寫一個php腳本來創建和下載一個zip文件。當我在本地主機上測試腳本時,下載工作正常,但是當它上傳到服務器時,出現問題:不是下載zip文件,而是在瀏覽器中顯示文件內容。PHP還是Apache? zip文件的內容是diplayed而不是下載zip文件

有人可以指出我正確的方向嗎?

代碼

$zip = new ZipArchive(); 
    $zip->open("$maand/zipfile.zip", ZipArchive::OVERWRITE); 
    $zip->addFile("$maand/ant/a_nb.txt", 'ant.txt'); 
    $zip->addFile("$maand/lim/l_nb.txt", 'lim.txt'); 
    $zip->addFile("$maand/oos/o_nb.txt", 'oos.txt'); 
    $zip->addFile("$maand/vla/v_nb.txt", 'vla.txt'); 
    $zip->addFile("$maand/wes/w_nb.txt", 'wes.txt'); 
    $zip->close(); 
    $filename = "zipfile.zip"; 
    $filepath = "$maand/"; 
// headers for zip downloads 
    header("Pragma: public"); 
    header("Expires: 0"); 
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
    header("Cache-Control: public"); 
    header("Content-type: application/zip"); 
    header("Content-Disposition: attachment; filename=\"".$filename."\""); 
    header("Content-Length: ".filesize($filepath.$filename)); 
    ob_end_flush(); 
    @readfile($filepath.$filename); 
+0

看看這裏: http://stackoverflow.com/questions/8485886/force-file-使用php下載-with-header您必須設置正確的標題。 – JustOnUnderMillions

+0

你不需要'ob_end_flush();' – bansi

回答

3

你缺少ob_start()

例如:

header('Content-Type: application/csv'); 
    header('Content-Disposition: attachement; filename="' . $download . '"'); 
    ob_start(); 
    $str = ''; 
    if(file_exists($file) === true){ 
     $str = file_get_contents($file); 
    } 
    ob_end_clean(); 
    echo $str; 
+0

犯了一個錯字:你的解決方案確實有效!謝謝! – StevenCl

+0

很高興爲你效勞! – a4arpan