2013-11-14 31 views
0

我需要在index.php中創建zip文件。我的代碼是:zip存檔和下載無法正常工作

$zip = new ZipArchive(); 

$DelFilePath="first.zip"; 

if(file_exists($_SERVER['DOCUMENT_ROOT']."/admin/Allorders/".$DelFilePath)) { 

     unlink ($_SERVER['DOCUMENT_ROOT']."/admin/Allorders/".$DelFilePath); 

} 
if ($zip->open($_SERVER['DOCUMENT_ROOT']."/admin/Allorders/".$DelFilePath, ZIPARCHIVE::CREATE) != TRUE) { 
     die ("Could not open archive"); 
} 
    $zip->addFile($_SERVER['DOCUMENT_ROOT']."/admin/index.php","file.php"); 

// close and save archive 


$file=$_SERVER['DOCUMENT_ROOT']."/admin/Allorders/".$DelFilePath; 

header('Content-Description: File Transfer'); 
header('Content-Type: application/octet-stream'); 
header('Content-Disposition: attachment; filename="'.basename($file).'"'); 
header('Content-Transfer-Encoding: binary'); 
header('Connection: Keep-Alive'); 
header('Expires: 0'); 
header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
header('Pragma: public'); 
header('Content-Length: ' . filesize($file)); 

我得到一個0字節的zip文件。我的代碼中有什麼問題?

回答

2

聲明所有標題後,您需要將實際數據回顯出來。所以:

header('Content-Description: File Transfer'); 
header('Content-Type: application/octet-stream'); 
header('Content-Disposition: attachment; filename="'.basename($file).'"'); 
header('Content-Transfer-Encoding: binary'); 
header('Connection: Keep-Alive'); 
header('Expires: 0'); 
header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
header('Pragma: public'); 
header('Content-Length: ' . filesize($file)); 
echo $data; 

其中$ data是zip壓縮文件的內容。

也試試zip上的一些var_dump()來查看它在內存中是否正常。

+0

謝謝@cen,你能告訴我如何獲得$ data變量的數據?,我的意思是鋤頭使用它,直到我得到0咬拉鍊文件 –

+0

我從來沒有使用ZipArchive類,所以我不知道。也許ZipArchive :: getStream與stream_get_contents()函數結合使用。請參閱PHP文檔。 – cen