小庚资源网 · 免费提供绿色软件、活动线报以及其他网络资源,好货不私藏!
当前位置:网站首页 > 技巧分享 > 其他分享 >正文

PHP将文件夹的文件压缩到Zip包里

作者:小编日期:2023-06-30浏览:5762分类:其他分享

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

以下是代码:

<?php
/*
 * Cumin云版权所有
 */

# 将文件夹的文件压缩到文件里
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, '/')),"/");

        $sourcePath=$parentPath.'/'.$dirName;//防止传递'folder'文件夹产生bug

        $z = new \ZipArchive();
        $z->open($outZipPath, \ZIPARCHIVE::CREATE);//建立zip文件
        $z->addEmptyDir($dirName);//建立文件夹
        folderToZip($sourcePath, $z, strlen("$parentPath/"));
        $z->close();
        return $outZipPath;
    }

    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);
    }
}


暂无评论,来添加一个吧。

取消回复欢迎发表评论:

Copyright© XGW9.COM版权所有〖小庚资源网〗
〖恒创科技〗为本站提供专业云计算服务  
本站发布的内容来源于互联网,如果有侵权内容,请联系我们删除!E-mail:xgzyw6@outlook.com
关于我们|我要投稿|免责声明|XML地图