I need a simple function that writes an array of files to one zip file. I found some code from an online tutorial and modified it slightly, but I can't seem to get it to work. It creates the zip file, but when I try and extract it I get an error:
Windows cannot complete the extraction.
The Compressed (zipped) Folder '...' is invalid.
Here's the code I'm working with:
public function create_zip($files = array(),$destination = '',$overwrite = false) {
//if the zip file already exists and overwrite is false, return false
if(file_exists($destination) && !$overwrite) { return 'file exists'; }
$valid_files = array();
if(is_array($files)) {
//cycle through each file
foreach($files as $file) {
//make sure the file exists
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
Zend_Debug::dump($valid_files);
if(count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if($zip->open($destination, ZIPARCHIVE::CREATE) !== true) {
return 'could not open zip: '.$destination;
}
//add the files
foreach($valid_files as $file) {
$zip->addFile($file);
}
//debug
Zend_Debug::dump($zip->numFiles);
Zend_Debug::dump($zip->status);
$zip->close();
//check to make sure the file exists
return file_exists($destination);
} else {
return 'no valid failes'. count($valid_files);
}
}
The debug statements are printing out the following:
For $valid_files - array of one file name (full path to file)
For $zip->numFiles - 1
For $zip->status - 0
The function returns true.
Any ideas on what I'm doing wrong?
Just needed to add slashes before the file names.
Found the answer here: using zipArchive addFile() will not add image to zip