PHP 压缩多文件 或 文件夹与文件压缩到统一文件详细代码

PHP 压缩多文件 或 文件夹与文件压缩到统一文件 详解

使用场景

因为我们公司 要 多个文件夹 和 文件 压缩放到一个 压缩包内,终于找到 万能的 PHP 压缩方法

一共两个 方法 话不多说直接上代码

    /**
     *
     * createZip - 创建压缩包,for文件夹/文件
     *
     * @param type string-or-array $from
     *        => 字符串 '/path/to/source/file/or/folder/'
     *        => 或者 包含字符串的数组  array('fileA','FolderA','fileB')
     * @param type string $to
     *        => 字符串 '/path/to/output.zip'
     * @return array
     *        => array(
     *             'success' => false,
     *             'message' => '失败原因',
     *             'data' => array(
     *                 'zipFile' => array(zip文件的信息)
     *             )
     *           )
     * @author Rudon[285744011@qq.com]
     *
     */
  public  function createZip($from=[], $to="")  {

    /* from  参数 主要是  文件夹名称路径 或者 文件名称路径
        to   参数是要 存放 的路径
     Env::get('root_path')  TP5 自带获取当前绝对路径信息
    */
      $from[] =    Env::get('root_path') . "/public/static/excelZip/1663657132/thumbnail";
      $from[] =    Env::get('root_path') . "/public/static/excelZip/1663657132/originalImage";
      $from[] =    Env::get('root_path') . "/public/static/excelZip/1663657132/2022-09-20-1663657132.xls";
       $to = Env::get('root_path') . "/public/static/excelZip/1663657132/1663657132.zip";
        /* Init   return 内容信息 可不用理会*/
        $return = array(
            'success' => false,
            'message' => '',
            'data' => array(
                'zipFile' => array(
                    'name' => '1663657132.zip',
                    'path_relative' => '',
                    'path_absolute' => '',
                    'url' => '1663657132.zip', // 自己添加吧
                    'size' => '',
                    'exists_before' => false
                )
            )
        );

        /* Check zip class */
        if (!class_exists('ZipArchive')) {
            $return['message'] = 'Missing ZipArchive module in server.';
            return $return;
        }

        /* Check right of write for target zip file */
        $zip = new \ZipArchive();
        if (!is_dir(dirname($to))) {
            mkdir(dirname($to), 0755, TRUE);
        }
        if (is_file($to)) {
            $return['data']['zipFile']['exists_before'] = true;
            if ($zip->open($to, \ZIPARCHIVE::OVERWRITE) !== TRUE) {
                $return['message'] = "Cannot overwrite: {$to}";
                return $return;
            }
        } else {
            if ($zip->open($to, \ZIPARCHIVE::CREATE) !== TRUE) {
                $return['message'] = "Could not create archive: {$to}";
                return $return;
            }
        }
        /* Check path of source files or folder */
        $source_path_including_dir = array();
        $prefix_relative_path_for_source = '';
        if (is_array($from)) {
            foreach ($from as $path) {
                if (file_exists($path)) {
                    if ($prefix_relative_path_for_source == '') {
                        $prefix_relative_path_for_source = (is_dir($path)) ? realpath($path) : realpath(dirname($path));
                    }
                    $source_path_including_dir[] = $path;
                } else {
                    $return['message'] = 'No such file or folder: ' . $path;
                    return $return;
                }
            }
        } elseif (file_exists($from)) {
            $prefix_relative_path_for_source = (is_dir($from)) ? realpath($from) : realpath(dirname($from));
            $source_path_including_dir[] = $from;
        } else {
            $return['message'] = 'No such file or folder: ' . $from;
            return $return;
        }
        $prefix_relative_path_for_source = rtrim($prefix_relative_path_for_source, '/') . '/';

        /* Get final list of files, no folder */
        $final_list_of_files = array();

        foreach ($source_path_including_dir as $path) {
            if (is_file($path)) {
                /* File */
                $final_list_of_files[] = $path;
            } else {
                /* Folder */
                $list_of_files = $this->recursive_get_files_by_path_of_folder($path);
                foreach ($list_of_files as $one) {
                    $final_list_of_files[] = $one;
                }
            }
        }

        if (!count($final_list_of_files)) {
            $return['message'] = 'No valid file or folder used to zip';
            return $return;
        }
        /* Begin to add to zip file */
        foreach ($final_list_of_files as $one_file) {
            //设置存放 路径名称
            $zip->addFile($one_file, substr($one_file, strripos($one_file, "excelZip/") + 9));
        }

        $zip->close();
        /* Return */
        $return['success'] = true;

        $return['data']['zipFile']['path_relative'] = $to;

       return  1;
    }


    /**
     * 获取文件夹下的文件列表,遍历模式
     *
     * @param type $dir
     * @param type $is_tree
     * @return string
     */
    public function recursive_get_files_by_path_of_folder($dir, $is_tree = false)
    {
        $files = array();
        $dir = preg_replace('/[\/]{1}$/i', '', $dir);
        if (is_dir($dir)) {
            if ($handle = opendir($dir)) {
                while (($file = readdir($handle)) !== false) {
                    if ($file != "." && $file != "..") {
                        if (is_dir($dir . "/" . $file)) {
                            $sub_list = $this->recursive_get_files_by_path_of_folder($dir . "/" . $file, $is_tree);
                            if ($is_tree) {
                                $files[$file] = $sub_list;
                            } else {
                                foreach ($sub_list as $one_sub_file) {
                                    $files[] = $one_sub_file;
                                }
                            }
                        } else {
                            $files[] = $dir . "/" . $file;
                        }
                    }
                }
                closedir($handle);
                return $files;
            }
        } else {
            $files[] = $dir;
            return $files;
        }
    }

心得体会

多分享,用到的点点赞!

今日分享语录

一定要加油!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值