Создание ZIP архива с вложенными папками

Функция для архивации папки и всех подпапок. Источником послужил ответ на stackoverflow (см. ниже). Мой вариант создаст архив со структурой папок начиная с $destination, а не от корня файловой системы (Windows). Требование: включенное zip расширение PHP.

function zip($source, $destination) {
  if (!extension_loaded('zip') || !file_exists($source)) {
    return false;
  }
  
  $zip = new ZipArchive();
  if (!$zip->open($destination, ZipArchive::CREATE | ZipArchive::OVERWRITE)) {
    return false;
  }
  
  $source = str_replace('\\', '/', realpath($source));
  
  if (is_dir($source) === true) {
    $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
    
    foreach ($files as $file) {
      $file = str_replace('\\', '/', $file);
      
      if (in_array(substr($file, strrpos($file, '/') + 1), array('.', '..'))) {
        // Ignore "." and ".." folders
        continue;
      }
      
      $file = realpath($file);
      
      if (is_dir($file) === true) {
        $zip->addEmptyDir($files->getSubIterator()->getSubPath());
      }
      else 
        if (is_file($file) === true) {
          $zip->addFromString($files->getSubIterator()->getSubPathname(), file_get_contents($file));
        }
    }
  }
  else 
    if (is_file($source) === true) {
      $zip->addFromString(basename($source), file_get_contents($source));
    }
  
  return $zip->close();
}


Оригинал: http://stackoverflow.com/a/1334949

Php ZIP
comments powered by Disqus