事情的经过是因为我正在写授权系统需要用到Zip相关的函数,因为Zip相关函数是PHP的扩展功能,之前没有了解过,还有太懒了一直拖着,直到今天我才写出来实现相关功能。
以下是代码:
open($outZipPath, \ZIPARCHIVE::CREATE);//建立zip文件
$z->addEmptyDir($dirName);//建立文件夹
folderToZip($sourcePath, $z, strlen("$parentPath/"));
$z->close();
return $outZipPath;
}
public static function folderToZip($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);
}
}