Extract directory inside zip

I am writing a script to extract files from a zip archive to the directory where the script is located.

Here is 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 great, but there is one problem. Zip contains an extra layer. (zip / directory / files), which extracts how this directory / files, not just files.

Is there any way to remove this extra layer?

Thank you for your help!

Joel Draper

+3
source share
1 answer

To prevent overwriting any files, you probably want to extract the zip file to a directory first. I would create a directory with a random name, unzip the zip into this director and then check 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>/"
}

, , , , Windows. , , :

+2

Source: https://habr.com/ru/post/1708280/


All Articles