php 生成壓縮包並下載
阿新 • • 發佈:2021-09-01
<?php namespace app\libs; class downLoadZip { public function downLoadFiles() { $exportPath = './qrcode'; $filename = $exportPath . '.zip'; $zip = new \ZipArchive(); //引數1:zip儲存路徑,引數2:ZIPARCHIVE::CREATE沒有即是建立 if (!$zip->open($filename, \ZIPARCHIVE::CREATE)) { echo "建立[exportPath.zip]失敗<br/>"; return; } //echo "建立[$exportPath.zip]成功<br/>"; $this->createZip(opendir($exportPath), $zip, $exportPath); $zip->close(); header("Cache-Control: public"); header("Content-Description: File Transfer"); header('Content-disposition: attachment; filename=' . basename($filename)); //檔名 header("Content-Type: application/zip"); //zip格式的 header("Content-Transfer-Encoding: binary"); //告訴瀏覽器,這是二進位制檔案 header('Content-Length: ' . filesize($filename)); //告訴瀏覽器,檔案大小 $this->deldir('./qrcode'); @readfile($filename); unlink('qrcode.zip'); //刪除伺服器壓縮檔案,釋放伺服器資源 } function createZip($openFile, $zipObj, $sourceAbso, $newRelat = '') { while (($file = readdir($openFile)) != false) { if ($file == "." || $file == "..") continue; /*源目錄路徑(絕對路徑)*/ $sourceTemp = $sourceAbso . '/' . $file; /*目標目錄路徑(相對路徑)*/ $newTemp = $newRelat == '' ? $file : $newRelat . '/' . $file; if (is_dir($sourceTemp)) { //echo '建立'.$newTemp.'資料夾<br/>'; $zipObj->addEmptyDir($newTemp);/*這裡注意:php只需傳遞一個資料夾名稱路徑即可*/ $this->createZip(opendir($sourceTemp), $zipObj, $sourceTemp, $newTemp); } if (is_file($sourceTemp)) { //echo '建立'.$newTemp.'檔案<br/>'; $zipObj->addFile($sourceTemp, $newTemp); } } } public function deldir($dir) { //先刪除目錄下的檔案: $dh = opendir($dir); while ($file = readdir($dh)) { if ($file != "." && $file != "..") { $fullpath = $dir . "/" . $file; if (!is_dir($fullpath)) { unlink($fullpath); } else { $this->deldir($fullpath); } } } } }