<?php
/* 使用方法
* HZip::zipDir('yourlife', 'yourlife.zip');
*/
class HZip
{
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包
*/
public static function Doc_to_zip($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();
}
/**
*解压zip包
* @param string $file 压缩文件路径
* @param string $path 解压路径,为空则以文件名为路径
*/
public static function Zip_to_doc($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();
return true;
}
return false;
}
}
$zip = new HZip();
#将文件压缩成zip
//$zip::Doc_to_zip('../study','./new.zip');
#直接将压缩里的文件加压到指定的路径
#将zip包解压到制定目录
$zip::Zip_to_doc('./new.zip','.new/');
?>
php操作zip文件
最新推荐文章于 2015-11-16 00:09:04 发布