Home » Php » remove directory structure when zipping files in PHP

remove directory structure when zipping files in PHP

Posted by: admin July 12, 2020 Leave a comment


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) {
        $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>';


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

            return true;

        } else {
           return false;

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


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:


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.

How to&Answers:

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

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


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.