php 將多個檔案壓縮成zip並下載到本地
阿新 • • 發佈:2018-12-30
廢話不多說,直接上程式碼
//這裡需要注意該目錄是否存在,並且有建立的許可權 $zipname = 'path/test.zip' //這是要打包的檔案地址陣列 $files = array("mypath/test1.txt","mypath/test2.pdf"); $zip = new ZipArchive(); $res = $zip->open($zipname, ZipArchive::CREATE); if ($res === TRUE) { foreach ($files as $file) { //這裡直接用原檔案的名字進行打包,也可以直接命名,需要注意如果檔名字一樣會導致後面檔案覆蓋前面的檔案,所以建議重新命名 $new_filename = substr($file, strrpos($file, '/') + 1); $zip->addFile($file, $new_filename); }
//關閉檔案
$zip->close();
//這裡是下載zip檔案 header("Content-Type: application/zip"); header("Content-Transfer-Encoding: Binary"); header("Content-Length: " . filesize($zipname)); header("Content-Disposition: attachment; filename=\"" . basename($zipname) . "\""); readfile($zipname); exit; }