PHPZip.class.php
2.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
/*
* File name: PHPZip 文件压缩类
* Author: wpp
*/
namespace Org\Net;
class PHPZip
{
/**
* 添加文件和子目录的文件到zip文件
*
* @param string $folder
* @param ZipArchive $zipFile
* @param int $exclusiveLength
* Number of text to be exclusived from the file path.
*/
private static function folderToZip($folder, &$zipFile, $exclusiveLength)
{
$handle = opendir($folder);
while (false !== $f = readdir($handle)) {
if ($f != '.' && $f != '..') {
$filePath = "$folder/$f";
// Remove prefix from file path before add to 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);
}
/**
* Zip a folder (include itself).
* Usage:
* HZip::zipDir('/path/to/sourceDir', '/path/to/out.zip');
*
* @param string $sourcePath
* Path of directory to be zip.
* @param string $outZipPath
* Path of output zip file.
* @param bool $dir_zip true|false 是否打包当前文件夹
*/
public function zipDir($sourcePath, $outZipPath, $dir_zip = true)
{
// 判断目录是否存在,若存在则删除
if (!file_exists($sourcePath)) {
return false;
}
// 目标路径
$outZipPath = iconv("UTF-8", "GBK", $outZipPath);
$pathInfo = $this->path_info($sourcePath);
$parentPath = $pathInfo['dirname'];
$dirName = $pathInfo['basename'];
$sourcePath = $parentPath . '/' . $dirName; // 防止传递'folder' 文件夹产生bug
$z = new \ZipArchive();
$z->open($outZipPath, \ZipArchive::CREATE); // 建立zip文件
// 如果开启打包文件夹
if ($dir_zip) {
$z->addEmptyDir($dirName); // 建立文件夹
self::folderToZip($sourcePath, $z, strlen("$parentPath/"));
} else {
self::folderToZip($sourcePath, $z, strlen("$sourcePath/"));
}
$z->close();
}
/**
* 解决中文乱码
*/
public function path_info($filepath)
{
$path_parts = array();
$path_parts['dirname'] = rtrim(substr($filepath, 0, strrpos($filepath, '/')), "/") . "/";
$path_parts['basename'] = ltrim(substr($filepath, strrpos($filepath, '/')), "/");
$path_parts['extension'] = substr(strrchr($filepath, '.'), 1);
$path_parts['filename'] = ltrim(substr($path_parts['basename'], 0, strrpos($path_parts['basename'], '.')), "/");
return $path_parts;
}
}