Here's a stack-based way to zip a directory. No recursion, no function, no class:
<?php
$zip = new ZipArchive();
$zip->open('test.zip', ZipArchive::CREATE);
$dirName = 'test';
if (!is_dir($dirName)) {
throw new Exception('Directory ' . $dirName . ' does not exist');
}
$dirName = realpath($dirName);
if (substr($dirName, -1) != '/') {
$dirName.= '/';
}
$dirStack = array($dirName);
$cutFrom = strrpos(substr($dirName, 0, -1), '/')+1;
while (!empty($dirStack)) {
$currentDir = array_pop($dirStack);
$filesToAdd = array();
$dir = dir($currentDir);
while (false !== ($node = $dir->read())) {
if (($node == '..') || ($node == '.')) {
continue;
}
if (is_dir($currentDir . $node)) {
array_push($dirStack, $currentDir . $node . '/');
}
if (is_file($currentDir . $node)) {
$filesToAdd[] = $node;
}
}
$localDir = substr($currentDir, $cutFrom);
$zip->addEmptyDir($localDir);
foreach ($filesToAdd as $file) {
$zip->addFile($currentDir . $file, $localDir . $file);
}
}
$zip->close();
?>