利用php的扩展zip功能实现多层目录的打包,案例是多个不同位置的文件分目录打包成指定的文件。
效果:
代码:
/**多级目录压缩 * @param $openFile string 打开的目录 * @param $zipObj object 实例化ZipArchive对象 * @param $sourcePath string 源目录路径,绝对路径,如/user/bing/xxxx/ * @param string $newRelat 相对目录的路径名称,如 image */ private static function createZip($openFile, $zipObj, $sourcePath, $newRelat = '') { while (($file = readdir($openFile)) != false) { if ($file == "." || $file == "..") continue; /*源目录路径(绝对路径)*/ $sourceTemp = $sourcePath . '/' . $file; /*目标目录路径(相对路径)*/ $newTemp = $newRelat == '' ? $file : $newRelat . '/' . $file; if (is_dir($sourceTemp)) { $zipObj->addEmptyDir($newTemp);/*这里注意:php只需传递一个文件夹名称路径即可*/ self::createZip(opendir($sourceTemp), $zipObj, $sourceTemp, $newTemp); } if (is_file($sourceTemp)) { $zipObj->addFile($sourceTemp, $newTemp); } } } /**打包下载 * @param $params * @return array */ public static function action_pack($params) { //基本的文件路径 $controller_path = 'plugin/app/' . $params['plugin_tag']; $view_path = 'plugin/app_view/' . $params['plugin_tag']; $static_path = 'static/plugins/' . $params['plugin_tag']; //临时储存位置 $temp_dir = $params['user_id'] . '/pack_app/'; if (!is_dir($temp_dir)) { if (! mkdir($temp_dir, 0777, true)){ return DataReturn('目录没有写入权限'.$temp_dir,-1); } } //最终目标 $zipName = $temp_dir . $params['plugin_tag'] . '.zip'; $zip = new \ZipArchive (); $zip->open($zipName, \ZipArchive::CREATE); if (is_dir($controller_path)){ self::createZip(opendir($controller_path), $zip, $controller_path,'controller'); } if (is_dir($view_path)){ self::createZip(opendir($view_path), $zip, $view_path,'view'); } if (is_dir($static_path)){ self::createZip(opendir($static_path), $zip, $static_path,'static'); } self::createZip(opendir($temp_dir), $zip, $temp_dir); $zip->close(); if (is_file($zipName)){ //todo 下载功能 } return DataReturn(3,-2); }