title: PHP Zip: Extract contents of a directory
body: <p>I need to extract the contents of a directory within a zip archive in to an output directory.</p>
  
  <p>The directory name inside the zip could be anything. However it will be the only directory in the base of the zip archive. There could be any number of files in the directory, in the zip archive, though.</p>
  
  <p>The file structure inside the zip would be along theses lines:</p>
  
  <pre><code>- d0001
    - My Folder
      - view.php
      - tasks.txt
    - file1.txt
    - picture1.png
    - document.doc
  </code></pre>
  
  <p>The contents of the output directory needs to look like this:</p>
  
  <pre><code>- My Folder
    - view.php
    - tasks.txt
  - file1.txt
  - picture1.png
  - document.doc
  </code></pre>
  
  <p>The code I currently have deletes the contents of the output directory and extracts the entire zip archive in to the directory:</p>
  
  <pre><code>function Unzip($source, $destination) {
      $zip = new ZipArchive;
      $res = $zip-&gt;open($source);
      if($res === TRUE) {
        $zip-&gt;extractTo($destination);
        $zip-&gt;close();
        return true;
      } else {
        return false;
      }
  }
  function rrmdir($dir, $removebase = true) {
      if(is_dir($dir)) {
          $objects = scandir($dir);
          foreach($objects as $object) {
              if($object != "." &amp;&amp; $object != "..") {
                  if(filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
              }
          }
          reset($objects);
          if($removebase == true)
            rmdir($dir);
      }
  }
  
  $filename = '/home/files.zip';
  $dest = '/home/myfiles/';
  
  if(is_dir($dest)) {
    rrmdir($dest, false);
  
    $unzip = Unzip($filename, $dest);
    if($unzip === true) {
      echo 'Success';
    } else
      echo 'Extraction of zip failed.';
  } else
    echo 'The output directory does not exist!';
  </code></pre>
  
  <p>All the function <code>rrmdir()</code> does is remove the contents of the output directory.</p>