Extract Directory Inside Zip

只愿长相守 提交于 2020-01-13 18:10:57

问题


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:


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:

  • time()
  • glob()
  • opendir()
  • readdir()
  • rename()


来源:https://stackoverflow.com/questions/859396/extract-directory-inside-zip

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!