Last active
March 22, 2021 19:01
-
-
Save b2z/a6eef1526248470ff096f9be88eeb6d4 to your computer and use it in GitHub Desktop.
Creates an archive of a directory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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