views:

573

answers:

1

Hey!

I'm writing a script to extract files from a zip archive into the directory that the script is located.

Here's my code:

$zip = new ZipArchive;
if ($zip->open('latest.zip') === TRUE) {
 $zip->extractTo('.');
 $zip->close();
 unlink('installer.php');
 echo 'it works!';
} else {
 echo 'failed';
}

This works fine, but there's one problem. The zip contains an extra layer. (zip/directory/files) which extracts like this directory/files rather then just the files.

Is there a way to remove this extra layer?

Thanks for your help!

Joel Drapper

+1  A: 

In order to prevent any files from getting overwritten, you probably want to extract the zip file into a directory first. I'd create a directory with a random name, extract the zip into that director and then check for any subdirectories:

<?php

// Generate random unzip directory to prevent overwriting
// This will generate something like "./unzip<RANDOM SEQUENCE>"
$pathname = './unzip'.time().'/';

if (mkdir($pathname) === TRUE) {

  $zip = new ZipArchive;

  if ($zip->open('latest.zip') === TRUE) {

    $zip->extractTo($pathname);

    // Get subdirectories
    $directories = glob($pathname.'*', GLOB_ONLYDIR);

    if ($directories !== FALSE) {

      foreach($directories as $directory) {

        $dir_handle = opendir($directory);

        while(($filename = readdir($dir_handle)) !== FALSE) {

          // Move all subdirectory contents to "./unzip<RANDOM SEQUENCE>/"
          if (rename($filename, $pathname.basename($filename)) === FALSE) {
            print "Error moving file ($filename) \n";
          }
        }
      }
    }

    // Do whatever you like here, for example:
    unlink($pathname.'installer.php');

  }

  // Clean up your mess by deleting "./unzip<RANDOM SEQUENCE>/"
}

I haven't tested this code, so, use at your own risk, also, it may not work as intended on Windows systems. Additionally, check out the documentation for all of the functions I used:

jakemcgraw
Thanks for your help! I don't need to create another directory as I know that the directory that the script is in will be empty. I just want to extract the files from within the zip(and the random useless directory layer) to the same folder as the script is located.
Joel Drapper