Skip to content

Instantly share code, notes, and snippets.

@b2z
Last active March 22, 2021 19:01
Show Gist options
  • Save b2z/a6eef1526248470ff096f9be88eeb6d4 to your computer and use it in GitHub Desktop.
Save b2z/a6eef1526248470ff096f9be88eeb6d4 to your computer and use it in GitHub Desktop.
Creates an archive of a directory
<?php
private function archiveDir($dir, $filename)
{
$rootPath = realpath($dir);
$zip = new ZipArchive;
if ($zip->open($filename, ZipArchive::CREATE) !== true)
{
Log::add('Failed to open ' . $filename, Log::ERROR, 'rdmedia');
return false;
}
// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file)
{
// Skip directories (they would be added automatically)
if (!$file->isDir())
{
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
if ($zip->addFile($filePath, $relativePath) === false)
{
Log::add('Failed to add file ' . $name, Log::ERROR, 'rdmedia');
}
}
}
$zip->close();
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment