Skip to content
Advertisement

Adding files into zip adds the folders containing the files

So I have a directory which contains at its root a files folder and inside it a test folder containing txt files, I then have this php code:

    function displayZip($name)
   $zip = new ZipArchive();
   $filename = "files/$name.zip";

  if ($zip->open($filename, ZipArchive::CREATE)!==TRUE) {
      exit("cannot open <$filename>n");
  }

  $dir = "files/$name/";
  createZip($zip, $dir);

  $zip->close();
  rmdir("files/$name");
 }

 function createZip($zip,$dir, $name){
  if (is_dir($dir)){

    if ($dh = opendir($dir)){
       while (($file = readdir($dh)) !== false){

         // If file
         if (is_file($dir.$file)) {
            if($file != '' && $file != '.' && $file != '..'){
               $zip->addFile($dir.$file);
            }
        }
   }
closedir($dh);
}
}

Which takes a name for the zip under the $name variable then specifies the full path under $filename then creates the zip archive, it then calls the createZip function which opens the directory of the same name of the zip and then adds the files under this directory inside the zip, however when I call displayZip(’test’) and then open the created zip, I see that it added the files/test/ folders inside it. So my question here is:

  1. where in the code does it add these folders, is it at the addFile line with $dir.$file part?
  2. What could I do to only get the files inside the zip?

Thanks in advance

Advertisement

Answer

By default, the ZipArchive adds the folders to the archive. You can remove the folders by specifying a “localname” as a second parameter in addFile(). That “localname” will be the structure within the zip archive. See https://www.php.net/manual/en/ziparchive.addfile.php for details.

The rmdir is likely not working because because the directory isn’t empty.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement