PHP代码实现Zip压缩文件夹功能
Zip压缩文件夹的PHP打包函数代码如下: ```php <?php function zipFolder($source, $destination) { $zip = new ZipArchive(); if (!$zip->open($destination, ZipArchive::CREATE)) { return false; } $source = realpath($source); if (is_dir($source)) { $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST); foreach ($files as $file) { $file = realpath($file); if (is_dir($file)) { $zip->addEmptyDir(str_replace($source . '/', '', $file . '/')); } else if (is_file($file)) { $zip->add
分享一个菜鸡源码自用的Zip压缩文件夹php打包函数代码,Zip相关函数是PHP的扩展功能,此函数可以直接复制使用。
以下是代码:
<?php#将文件夹的文件压缩到文件里classZip{/***将目标文件夹下的内容压缩到zip中(zip包含文件夹目录)*@param$sourcePath*文件夹路径例:/home/test*@param$outZipPath*zip文件名(包含路径)例:/home/zip_file/test.zip*@returnstring*/publicstaticfunctionzipFolder($sourcePath,$outZipPath){$parentPath=rtrim(substr($sourcePath,0,strrpos($sourcePath,'/')),"/")."/";$dirName=ltrim(substr($sourcePath,strrpos($sourcePath,'/')),"/");$sourcePath=$parentPath.'/'.$dirName;//防止传递'folder'文件夹产生bug$z=new\ZipArchive();$z->open($outZipPath,\ZIPARCHIVE::CREATE);//建立zip文件$z->addEmptyDir($dirName);//建立文件夹folderToZip($sourcePath,$z,strlen("$parentPath/"));$z->close();return$outZipPath;}publicstaticfunctionfolderToZip($folder,&$zipFile,$exclusiveLength){$handle=opendir($folder);while(false!==$f=readdir($handle)){if($f!='.'&&$f!='..'){$filePath="$folder/$f";//在添加到zip之前从文件路径中删除前缀$localPath=substr($filePath,$exclusiveLength);if(is_file($filePath)){$zipFile->addFile($filePath,$localPath);}elseif(is_dir($filePath)){//添加子文件夹$zipFile->addEmptyDir($localPath);self::folderToZip($filePath,$zipFile,$exclusiveLength);}}}closedir($handle);}}