Before marking this post as a duplicate, please note that I have already searched for answer on SO and the once I've found so far (listed below) haven't been exactly what I've been looking for.
- How to [recursively] Zip a directory in PHP?
- using zipArchive addFile() will not add image to zip
- ZipArchive - addFile won't work
Those are just some of the ones I've looked at.
My problem is this: I can't use addFromString, I have to use addFile, it's a requirement of the task.
I've already tried a couple of ways, here's my current iteration:
public function getZippedFiles($path)
{
$real_path = WEBROOT_PATH.$path;
$files = new RecursiveIteratorIterator (new RecursiveDirectoryIterator($real_path), RecursiveIteratorIterator::LEAVES_ONLY);
//# create a temp file & open it
$tmp_file = tempnam($real_path,'');
$zip_file = preg_replace('"\.tmp$"', '.zip', $tmp_file);
$zip = new ZipArchive();
$zip->open($zip_file, ZipArchive::CREATE);
foreach ($files as $name=>$file)
{
error_log(print_r($name, true));
error_log(print_r($file, true));
if ( ($file == ".") || ($file == "..") )
{
continue;
}
$file_path = $file->getRealPath();
$zip->addFile($file_path);
}
$zip->close();
}
When I try to open the resulting file, I get told that "Windows cannot open the folder. The Compressed(zipped) Folder '' is invalid."
I've managed to succesfully complete the task using addFromString, like so:
$file_path = WEBROOT_PATH.$path;
$files = array();
if (is_dir($file_path) == true)
{
if ($handle = opendir($file_path))
{
while (($file = readdir($handle)) !== false)
{
if (is_dir($file_path.$file) == false)
{
$files[] = $file_path."\\".$file;
}
}
//# create new zip opbject
$zip = new ZipArchive();
//# create a temp file & open it
$tmp_file = tempnam($file_path,'');
$zip_file = preg_replace('"\.tmp$"', '.zip', $tmp_file);
$zip->open($zip_file, ZipArchive::CREATE);
//# loop through each file
foreach($files as $file){
//# download file
$download_file = file_get_contents($file);
//#add it to the zip
$zip->addFromString(basename($file),$download_file);
}
//# close zip
$zip->close();
}
}
}
The above is mostly just copied straight from some example code I saw somewhere. If anyone can point me in a good direction I'd be very grateful!
***** UPDATE ***** I added an if around the close like this:
if (!$zip->close()) {
echo "failed writing zip to archive";
}
The message gets echoed out, so obviously the problem is there. I've also checked to make sure the $zip->open()
works, and I've confirmed that it is opening it without a problem.