-1

I have a script which allows users to upload a ZIP folder. Some users select individual files, and ZIP them up so when uncompressed there are multiple files, however some ZIP entire folders, so when they're uncompressed you just get one folder.

What I want to do, is check if the only contents of an unzipped folder is another folder, and if it is, move all the files from that folder down into the previous one, and delete the original folder.

What would the best way of doing this be?

Benedict Lewis
  • 2,733
  • 7
  • 37
  • 78

1 Answers1

0

In other words, you want to flatten the directory structure of a zip archive. There are lots of ways to do this.

Unzip, then flatten folder structure

One would be to unzip the zip archive and then use a DirectoryIterator to walk files and folders. If a folder is detected, move/copy it's file content to the extraction dir and delete the folder afterwards. That would flatten the dir structure with every iteration on a folder.

https://stackoverflow.com/a/17087268/1163786

ZipArchive - unzip without folder

Another approach would be to unzip the zip archive, without taking care about the paths stored in it, like so:

$path = 'zipfile.zip'  

$zip = new ZipArchive;

if ($zip->open($path) === true) {
    for($i = 0; $i < $zip->numFiles; $i++) {
        $filename = $zip->getNameIndex($i);
        $fileinfo = pathinfo($filename);
        copy("zip://".$path."#".$filename, "/your/new/destination/".$fileinfo['basename']);
    }                   
    $zip->close();                   
}

unzip -j or 7z -e

Finally, it's tagged as PHP question, but: If you use unzip on the CLI, then use the -j option. Ìt stands for "junk paths", meaning that the archive's directory structure is not recreated, when unzipping and all files are stored in the extraction directory (by default, the current one).

It's e (to ignore paths), instead of x (with full paths) on 7z. http://sevenzip.sourceforge.jp/chm/cmdline/commands/extract.htm

Community
  • 1
  • 1
Jens A. Koch
  • 39,862
  • 13
  • 113
  • 141