Advertisement
jayelkaake

Recursively zip a folder with PHP

Mar 16th, 2015
585
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.26 KB | None | 0 0
  1.     /**
  2.      * Zips a folder provided to the destination zip file
  3.      * @param  string $source      path to folder you want to zip
  4.      * @param  string $destination destination zip file (will be created if it doesn't already exist)
  5.      * @return boolean              true if successful
  6.      */
  7.     public function zip($source, $destination)
  8.     {
  9.         if (!extension_loaded('zip') || !file_exists($source)) {
  10.             return false;
  11.         }
  12.  
  13.         $zip = new ZipArchive();
  14.         if(!$zip->open($destination, ZIPARCHIVE::CREATE)) {
  15.             return false;
  16.         }
  17.  
  18.         $source = str_replace('\\', DIRECTORY_SEPARATOR, realpath($source));
  19.         $source = str_replace('/', DIRECTORY_SEPARATOR, $source);
  20.  
  21.         if(is_dir($source) === true) {
  22.             $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
  23.  
  24.             foreach ($files as $file) {
  25.                 $file = str_replace('\\', DIRECTORY_SEPARATOR, $file);
  26.                 $file = str_replace('/', DIRECTORY_SEPARATOR, $file);
  27.  
  28.                 if ($file == '.' || $file == '..' || empty($file) || $file==DIRECTORY_SEPARATOR) continue;
  29.                 // Ignore "." and ".." folders
  30.                 if ( in_array(substr($file, strrpos($file, DIRECTORY_SEPARATOR)+1), array('.', '..')) )
  31.                     continue;
  32.  
  33.                 $file = realpath($file);
  34.                 $file = str_replace('\\', DIRECTORY_SEPARATOR, $file);
  35.                 $file = str_replace('/', DIRECTORY_SEPARATOR, $file);
  36.  
  37.                 if (is_dir($file) === true) {
  38.                     $d = str_replace($source . DIRECTORY_SEPARATOR, '', $file );
  39.                     if(empty($d)) continue;
  40.                     print "Making DIRECTORY {$d}<Br>";
  41.                     $zip->addEmptyDir($d);
  42.                 } elseif (is_file($file) === true) {
  43.                     $zip->addFromString(str_replace($source . DIRECTORY_SEPARATOR, '', $file), file_get_contents($file));
  44.                 } else {
  45.                     // do nothing
  46.                 }
  47.             }
  48.         } elseif (is_file($source) === true) {
  49.             $zip->addFromString(basename($source), file_get_contents($source));
  50.         }
  51.  
  52.         return $zip->close();
  53.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement