Extract Directory Inside Zip

为君一笑 提交于 2019-12-05 19:41:14

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:

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