递归压缩文件夹

/**
 * 文件夹压缩
 * @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);

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章