在PHP中压缩文件时删除目录结构 [英] remove directory structure when zipping files in PHP

查看:199
本文介绍了在PHP中压缩文件时删除目录结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中压缩文件时遇到了一个问题。我有一个压缩文件数组的功能,这些文件都在不同的目录中。该函数如下所示:

I have run into a bit of a problem when zipping files in PHP. I have a function which zips an array of files, these files are all in different directories. The function looks like :

function create_zip($files = array(),$destination = '',$overwrite = false,$add_to_db=true) {
    print_r($files);
        $zip = new ZipArchive();
        if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
            return false;
        }
        for($i=0;$i < count($files); $i++) {
            //echo $files[$i].'<br>';
            $zip->addFile($files[$i],$files[$i]);
        }



        $zip->close();

        if(file_exists($destination)) {
       //  echo("Success");
       if($add_to_db == true) { add_file($destination); }

            return true;

        } else {
        //echo("Failed");
           return false;
        }
    }

当用户下载并解压缩zip时,其结构文件就像:

When a user downloads and extracts the zip the structure of files is like :

folder/folder2/file1.jpg
folder/file2.jpg
folder/folder2/folder3/file3.jpg

我的问题是,是否可以让PHP放置所有文件在zip的根目录中,并忽略给定的结构。因此,提取的文件将如下所示:

My question is, is it possible to have PHP place all the files in the root of the zip and ignore the given structure. So the extracted files would look like:

/file1.jpg
/file2.jpg
/file3.jpg

我能想到的唯一解决方案是将所有文件移动到一个文件夹中,然后将其压缩

The only solution I could think of was moving all the files into a folder and then zipping this folder, but this seemed like overkill.

推荐答案

仅将第二个参数的文件名(无路径)指定为 addFile()

Specify just a filename (no path) for the 2nd parameter to addFile():

$zip->addFile( $files[$i], basename($files[$i]) );

https://www.php.net/manual/zh/ziparchive.addfile.php

是请注意,如果您尝试添加具有相同基本名称的多个文件(例如 folder1 / foo.jpg folder2 / foo.jpg ),您将覆盖第一个,而只有第二个将最终出现在zip文件中。

Be aware that if you attempt to add multiple files with the same basename (e.g. folder1/foo.jpg and folder2/foo.jpg), you'll overwrite the first one and only the second one will end up in the zip file.

这篇关于在PHP中压缩文件时删除目录结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆