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

souziyuan 2023-7-14 57 7/14

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

以下是代码:

搜资源-全网资源一网打尽www.souziyuan.top<?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);
    }
}

- THE END -
0

本站提供的资源,都来自网络,版权争议与本站无关,所有内容及软件的文章仅限用于学习和研究目的。不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负,我们不保证内容的长久可用性,通过使用本站内容随之而来的风险与本站无关,您必须在下载后的24个小时之内,从您的电脑/手机中彻底删除上述内容。如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。侵删请致信邮箱souziyuan@outlook.com

共有 0 条评论

您必须 后可评论