zip.class.php
2.2 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
<?php
class Zip {
/**
* 打包
*
* @param $path
* @param $save
*/
public static function archive($path, $save) {
$zip = new ZipArchive();
if ($zip -> open($save, ZipArchive :: OVERWRITE) === true) {
self :: addZip($path, $zip);
$zip -> close();
}
}
/**
* 添加文件或文件夹到zip对象
*
* @param string $path
* @param ZipArchive $zip
*/
private static function addZip($path, $zip) {
$handler = opendir($path);
while (($file = readdir($handler)) !== false) {
if ($file != '.' && $file != '..') {
if (is_dir($path . DIRECTORY_SEPARATOR . $file)) {
self :: addZip($path . DIRECTORY_SEPARATOR . $file, $zip);
} else {
$zip -> addFile($path . DIRECTORY_SEPARATOR . $file);
}
}
}
closedir($handler);
}
/**
* 解压文件
*
* @param string $file 压缩文件路径
* @param string $path 解压路径,为空则以文件名为路径
*/
public static function extra($file, $path = null) {
if (!isset($path)) {
$array = explode('.', $file);
$path = reset($array);
}
$zip = new ZipArchive();
if ($zip -> open($file) === true) {
$zip -> extractTo($path);
$zip -> close();
}
}
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);
}
public static function zipDir($sourcePath, $outZipPath) {
$pathInfo = pathInfo($sourcePath);
$parentPath = $pathInfo['dirname'];
$dirName = $pathInfo['basename'];
$sourcePath = $parentPath . '/' . $dirName; //防止传递'folder' 文件夹产生bug
$z = new ZipArchive();
$z -> open($outZipPath, ZIPARCHIVE :: CREATE); //建立zip文件
$z -> addEmptyDir($dirName); //建立文件夹
self :: folderToZip($sourcePath, $z, strlen("$parentPath/"));
$z -> close();
}
}