52 lines
1.5 KiB
PHP
52 lines
1.5 KiB
PHP
<?php
|
|
|
|
namespace Repository;
|
|
/**
|
|
* 压缩zip
|
|
* Class LogRepositories
|
|
* @package repositories
|
|
*/
|
|
class ZipRepository
|
|
{
|
|
|
|
/**
|
|
* description:主方法:生成压缩包
|
|
* @author: MY
|
|
* @param $dir_path 想要压缩的目录
|
|
* @param $zipName 压缩后的文件名
|
|
* @return string
|
|
*/
|
|
public static function zip($dir_path, $zipName)
|
|
{
|
|
$zip = new \ZipArchive();
|
|
if ($zip->open($zipName, \ZIPARCHIVE::OVERWRITE | \ZIPARCHIVE::CREATE) !== TRUE) {
|
|
return false;
|
|
}
|
|
self::addFileToZip($dir_path, $zip);
|
|
$zip->close();
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* 将文件添加到zip
|
|
* @param $path
|
|
* @param $zip
|
|
*/
|
|
public static function addFileToZip($path, $zip) {
|
|
$handler = opendir($path); //打开当前文件夹由$path指定。
|
|
while (($filename = readdir($handler)) !== false) {
|
|
//忽略 '.' 和 '..'
|
|
if ($filename != "." && $filename != "..") {
|
|
// 如果读取的某个对象是文件夹,则递归
|
|
if (is_dir($path . "/" . $filename)) {
|
|
self::addFileToZip($path . "/" . $filename, $zip);
|
|
} else {
|
|
// 将文件加入zip对象, 如果不带第二个参数的话会附加上文件目录路径
|
|
$zip->addFile($path . "/" . $filename, basename($path . "/" . $filename));
|
|
}
|
|
}
|
|
}
|
|
@closedir($path);
|
|
}
|
|
|
|
} |