PHP zip压缩文件及解压

   PHP zip压缩文件及解压 

        利用ZipArchive 类实现 只有有函数。界面大家自己写

ZipArchive(PHP 5.3 + 已自带不需要安装dll)

 

 1 /**
 2  * 文件解压
 3  * @param $zipFile 要解压的文件
 4  * @param $toPath   解压到拿个目录
 5  * @return bool
 6  */
 7 function zipExtract($zipFile, $toPath)
 8 {
 9     if (empty($zipFile) || empty($toPath)) return false;
10     $zip = new ZipArchive();
11     $zip->open($zipFile);
12     $return = $zip->extractTo($toPath);
13     $zip->close();
14     return $return;
15 }
16 
17 /**
18  * 文件压缩 需要dirList函数支持
19  * @param $zipFileName 要保存的zip文件名
20  * @param $toPath      路径
21  * @return bool
22  */
23 function ZipPack($zipFileName, $toPath)
24 {
25     $zip = new ZipArchive();
26     $zip->open($zipFileName, ZipArchive::OVERWRITE);
27     $toPath = str_replace('\\', '/', substr($toPath, -1) !== '/' ? $toPath . '/' : $toPath);
28     $fileList = dirList($toPath);
29     foreach ($fileList as $file) {
30         if (is_dir($file)) {
31             $file = str_replace($toPath, '', $file);
32             $zip->addEmptyDir($file);
33         } else {
34             $_file = str_replace($toPath, '', $file);
35             $zip->addFile($file, $_file);
36         }
37     }
38     $zip->close();
39     return empty($fileList) ? false : true;
40 }
41 
42 
43 /**
44  *
45  * 遍历指定文件夹下的文件及文件夹
46  * @param $path  要遍历的路径
47  * @param $dir   是否需要遍历子目录  默认遍历 如果为假 则不遍历
48  * @return array|bool   返回一维数组
49  */
50 function dirList($path,$dir=true)
51 {
52     $path = str_replace('\\', '/', substr($path, -1) !== '/' ? $path . '/' : $path);
53     if (!is_dir($path)) return false;
54     $return = array();
55     if ($handle = opendir($path)) {
56         while (false !== ($file = readdir($handle))) {
57             if ($file == '.' || $file == '..') continue;
58             $file = $path . $file;
59             $return[] = $file;
60             if (is_dir($file) && $dir) {
61                 $return['dir'] = dirList($file);
62                 foreach ($return['dir'] as $val) $return[] = $val;
63             }
64         }
65         closedir($handle);
66     }
67     unset($return['dir']);
68     return $return;
69 }

 

posted @ 2013-12-23 18:14  iyoule  阅读(291)  评论(0编辑  收藏  举报