Wednesday, October 13, 2010

How to [recursively] Zip a directory in PHP?

You can Zip a directory with ZipArchive Class in PHP easily.


<?php
function archive($path, $archive, $pathcleaning = false){
$zip = new ZipArchive();
if ($zip->open($archive, ZIPARCHIVE::CREATE) !== TRUE) {  die ("Could not open archive");  }
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
foreach ($iterator as $key=>$value) 
if(basename($key) != '.' && basename($key) != '..'){
$zip->addFile(realpath($key), $pathcleaning ? str_replace($path, '', $key) : $key) or die ("ERROR: Could not add file: $key");
}
$zip->close();
}


// zip a directory
archive('data/', 'data.zip', true);


// get the zip file
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="data.zip"');
header('Content-Transfer-Encoding: binary');
readfile('data.zip');
?>

No comments:

Post a Comment