Even better! I took a bit of interest in this (I have the perfect use for it) and decided to go with it. You should add these two functions to the zipfile class and call add_dir_recur() as in the example to recursively add a directory, including all files and even empty folders. This is based upon the function du() I found on php.net a while ago (which calculates the total size of the files in a directory), then modified to track the number of files and dirs, then adapted for this use. This was written and fully tested for Windows servers but you can probably just reverse the slashes for Unix-compatability. Enjoy!
PHP Code:
//Add me to your zipfile class
function add_dir_recur($location) {
//Add a trailing slash
if (substr($location, -1, 1) != '\\')
$location .= '\\';
return $this -> add_dir_recur_helper($location, $location);
}
//Add me to your zipfile class
function add_dir_recur_helper($root, $location) {
if (!$location || !is_dir($location))
return 0;
$size = 0;
$files = 0;
$dirs = 0;
$all = opendir($location);
while ($file = readdir($all)) {
if (is_dir($location.'\\'.$file) and $file != ".." and $file != ".") {
$temp = $this -> add_dir_recur_helper($root, $location.'\\'.$file);
$size += $temp['size'];
$files += $temp['files'];
$dirs += $temp['dirs'] + 1;
$this -> add_dir(str_replace($root.'\\', '', $location.'\\'.$file).'/');
unset($temp);
} elseif (!is_dir($location.'\\'.$file)) {
$stats = stat($location.'\\'.$file);
$size += $stats['size'];
$files++;
$filedata = file_get_contents($location.'\\'.$file);
if ($location == $root)
$this -> add_file($filedata, $file);
else
$this -> add_file($filedata, str_replace($root.'\\', '', $location.'\\'.$file));
unset($filedata);
}
unset($file);
}
closedir($all);
unset($all);
return array('size' => $size, 'files' => $files, 'dirs' => $dirs);
}
//Example usage:
$zipfile = new zipfile();
//It doesn't matter if there's a trailing slash
$info = $zipfile -> add_dir_recur('D:\test\path');
echo number_format($info['size'])." bytes in ".$info['files']." files and ".$info['dirs']." directories added to test.zip";
file_put_contents('D:\folder\test.zip', $zipfile -> file());
Bookmarks