Any ideas on why this is perfectly working in my localhost but not in the server where I uploaded it to? In the server, it creates the zip but does not create the folders, it puts all the files inside the .zip, with no folders distinction.
function rzip($source, $destination) {
// create object
$zip = new ZipArchive();
// open archive
if ($zip->open($destination, ZIPARCHIVE::CREATE) !== TRUE) {
die ("Could not open archive");
}
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source));
foreach ($iterator as $key=>$value) {
$new_filename = substr($key,strrpos($key,"/") + 1);
$zip->addFile(realpath($key), $new_filename) or die ("ERROR: Could not add file: $key");
}
$zip->close();
}
You are mis-using (or not using) the
RecursiveDirectoryIteratorin places.The first point is that you will iterate over the dot folders (
.and..) which is probably undesired; to stop this, use theSKIP_DOTSflag.Next, there are tools to get the file’s path relative to the main directory being iterated over and to get the real path too; using the
getSubPathname()andgetRealpath()methods, respectively.The above is only an answer because it’s too long for a comment. Nothing above answers why, “this is perfectly working in my localhost but not in the server“.