开发者

remove directory structure when zipping files in PHP

开发者 https://www.devze.com 2023-02-15 05:24 出处:网络
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 :

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

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

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.


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

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

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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号