php使用ZipArchive进行压缩目录下文件成zip

作者:Liaodeity - 2020年10月28日

1、可以将一个目录下的文件,进行压缩打包成zip。代码函数如下

function zip ($name, $path){
    //压缩
    if (!file_exists ($path)) {
        return false;
    }
    $current_dir = opendir ($path);
    while (($file = readdir ($current_dir)) !== false) {
        $sub_dir = $path . DIRECTORY_SEPARATOR . $file;
        if ($file == '.' || $file == '..') {
            continue;
        }
        if (is_file ($sub_dir)) {    //如果是文件,进行赋值
            $files[] = $file;
        }
    }
    if (empty($files)) {
        return false;
    }
    $zip_filename = $path.'/' . $name . '_' . date ('YmdHis') . '.zip';
    @unlink ($zip_filename);
    if (!file_exists ($zip_filename)) {
        touch ($zip_filename);
        $zip = new ZipArchive();
        $ret = $zip->open ($zip_filename, ZipArchive::OVERWRITE);
        if ($ret !== true) {
            printf ('Failed with code %d', $ret);
        } else {
            if (!empty($files)) {
                foreach ($files as $file) {
                    $zip->addFile ($path . '/' . $file, $file);
                }
            }
            $zip->close ();
        }
    }

    return $zip_filename;
}

2、调用函数进行打包压缩,第一个参数为zip的文件名前缀,第二个参数为打包目录地址。

zip('files','storage');

3、效果如下图,会在打包目录生成zip压缩包

本文作者: Liaodeity

本文链接: https://www.jianbaizhan.com/article/696

版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!


 请勿发布不友善或者负能量的内容。审查将对发布广告等违规信息进行处罚!