吃瓜代码:PHP将文件夹的文件压缩到Zip包里

瓜农17gua.com 吃瓜代码评论32字数 1186阅读模式
广告也精彩

今日吃瓜代码:PHP将文件夹的文件压缩到Zip包里

事情的经过是因为我正在写授权系统需要用到Zip相关的函数,因为Zip相关函数是PHP的扩展功能,之前没有了解过,还有太懒了一直拖着,直到今天我才写出来实现相关功能。

文章源自很文博客https://www.17gua.com/吃瓜网-https://www.17gua.com/92406.html

以下是代码:文章源自很文博客https://www.17gua.com/吃瓜网-https://www.17gua.com/92406.html

<?php
/*
* Cumin云版权所有
*/文章源自很文博客https://www.17gua.com/吃瓜网-https://www.17gua.com/92406.html

# 将文件夹的文件压缩到文件里
class Zip
{
/**
* 将目标文件夹下的内容压缩到zip中(zip包含文件夹目录)
* @param $sourcePath *文件夹路径 例: /home/test
* @param $outZipPath *zip文件名(包含路径) 例: /home/zip_file/test.zip
* @return string
*/
public static function zipFolder($sourcePath, $outZipPath)
{
$parentPath = rtrim(substr($sourcePath, 0, strrpos($sourcePath, '/')),"/")."/";
$dirName = ltrim(substr($sourcePath, strrpos($sourcePath, '/')),"/");文章源自很文博客https://www.17gua.com/吃瓜网-https://www.17gua.com/92406.html

$sourcePath=$parentPath.'/'.$dirName;//防止传递'folder'文件夹产生bug文章源自很文博客https://www.17gua.com/吃瓜网-https://www.17gua.com/92406.html

$z = new \ZipArchive();
$z->open($outZipPath, \ZIPARCHIVE::CREATE);//建立zip文件
$z->addEmptyDir($dirName);//建立文件夹
folderToZip($sourcePath, $z, strlen("$parentPath/"));
$z->close();
return $outZipPath;
}文章源自很文博客https://www.17gua.com/吃瓜网-https://www.17gua.com/92406.html

public static function folderToZip($folder, &$zipFile, $exclusiveLength)
{
$handle = opendir($folder);
while (false !== $f = readdir($handle)) {
if ($f != '.' && $f != '..') {
$filePath = "$folder/$f";
// 在添加到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);
}
}文章源自很文博客https://www.17gua.com/吃瓜网-https://www.17gua.com/92406.html

工具:作品在线观看

女优:最新作品观看

中文:国语在线观看

weinxin
我的微信
扫一扫更精彩
大家的支持是我更新的动力!!!
 
广告也精彩
匿名

发表评论

匿名网友
:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:
确定

拖动滑块以完成验证