/** * 文件夾壓縮 * @param string $path 文件夾絕對路徑 * @param string $zipName 壓縮文件名稱 * @return */ function fileZip($path,$zipName) { $uploadPath = '/var/www/uploadfiles/'; $path = rtrim($path,'/').'/'; $zipFile = $uploadPath . $zipName . '.zip'; if(!file_exists($zipFile)){ $zipFile = iconv('UTF-8','GB2312//IGNORE', $zipFile); touch($zipFile); } $zip = new \ZipArchive(); if($zip->open($zipFile, \ZipArchive::OVERWRITE)=== TRUE){ $this->addFileToZip($path, $zip); //調用方法,對要打包的根目錄進行操作,並將ZipArchive的對象傳遞給方法 $zip->close(); //關閉處理的zip文件 } //$this->delDirAndFile($path); //刪除文件夾,參考上篇文章 return $zipFile; }
/** * 遞歸壓縮 * @param string $path 文件夾絕對路徑 * @return */ function addFileToZip($path,$zip){ $file=scandir($path); foreach ($file as $value){ if($value != '.' && $value != '..'){ if(is_dir($path.$value) == true){ //目錄 $this->addFileToZip($path.$value."/", $zip); }else{ //文件 $zip->addFile($path.$value,explode(config('scsCommon.uploadPath'),$path)[1].$value); } } } }
fileZip($path,$zipName);