remove directory structure when zipping files in P

2019-06-17 03:26发布

问题:

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.

回答1:

Found the answer in another question

php creating zips without path to files inside the zip