PHP使用ZipArchive压缩、解压缩、加密压缩包等
<?php
use ZipArchive;
class Zip
{
/**
* @var array $files 需要压缩的文件或文件夹
*/
public $files = [];
/**
* 排除的文件
*/
public $notFile = [];
/**
* 压缩或者解压密码
*/
public $passowrd = null;
//压缩包名字及输出地址
public $zipName = 'package.zip';
//检测的根目录,默认为APP根目录
public $rootPath = AR;
private function addDir($folder, $zipFile, $rootPath, $folderSub = null)
{
// $folder = $this->rootPath . $folderb;
if (is_dir($folder)) {
$handle = opendir($folder);
while (false !== $f = readdir($handle)) {
if ($f != '.' && $f != '..') {
// Remove prefix from file path before add to zip.
$localPath = substr($filePath, $rootPath);
if (is_file($filePath)) {
$this->addFile($filePath, $localPath, $zipFile);
} elseif (is_dir($filePath)) {
// Add sub-directory.
$zipFile->addEmptyDir($localPath);
$this->addDir($filePath, $zipFile, $rootPath, $folderSub);
}
}
}
closedir($handle);
} else {
$this->addFile($folder, $folderSub, $zipFile);
}
}
private function addFile($filePath, $localPath, $zipFile)
{
$zipFile->addFile($filePath, $localPath);
if ($this->passowrd) {
$zipFile->setEncryptionName($localPath, ZipArchive::EM_AES_256);
}
}
/**
* 打包成ZIP
*/
public function zip()
{
$zip = new ZipArchive();
$zip->open(AR . $this->zipName, ZIPARCHIVE::CREATE);
if ($this->passowrd) {
$zip->setPassword($this->passowrd);
}
foreach ($this->files as $row) {
$pathInfo = pathinfo($this->rootPath . $row);
is_dir($this->rootPath . $row) ? $zip->addEmptyDir($pathInfo['basename']) : '';
$z = $this->addDir($this->rootPath . $row, $zip, strlen($pathInfo['dirname'] . '/'), $row);
}
foreach ($this->notFile as $row) {
$zip->deleteName($row);
}
$zip->close();
return $z;
}
/**
* 解压压缩包
*/
public function uzip($file, $path)
{
$zip = new ZipArchive();
$this->passowrd ? $zip->setPassword($this->passowrd) : '';
$zip->open($file);
$zip->extractTo($path);
$zip->close();
}
}
为防止网络爬虫,已删除关键代码,如有需要请发送博客地址到下边提示的邮箱里
本文来自博客园,作者:小枫同学,除网络转载的部分,其他版权属于作者和博客园所有,未经作者或博客园许可,禁止转载、复制、重新发布完整或者部分文字、代码、图片等信息,否则将保留追究法律责任的权利(如博客侵权了您的作品,本人再次表示抱歉,请将原创地址发送至下文邮箱,核实后立刻删除。)。查阅文章的同学,由于网络爬虫严重,有些代码并不会完整贴出来或者存在bug,不过你可以发送邮件到xfstune@126.com获取新代码,记得附上文章链接