When I trying to open my zip file which is generated by PHP Zip Archive, there is an alert showing
"Windows cannot open the folder. The Compressed (zipped) Folder 'filename' is invalid." error opening in Windows Explorer.
But I can open the file through 7-zip. In some reason, I have to ensure the zip file can open by Windows Explorer. Is there any problem when I generated the zip file? Please help!
function create_a_zip($files = array(),$dest = '',$root_folder,$overwrite = false) {
if(file_exists($dest) && !$overwrite) {
return false;
}
$valid_files = array();
if(is_array($files)) {
foreach($files as $file) {
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
if(count($valid_files)) {
$zip = new ZipArchive();
if($zip->open($dest,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
foreach($valid_files as $valid_file) {
if(is_dir($valid_file) === true){
foreach(glob($valid_file . '/*') as $file){
$zip->addFile($file, $root_folder . $file);
}
}else if (is_file($valid_file) === true){
$zip->addFile($valid_file, $root_folder . $valid_file);
}
}
$zip->close();
return file_exists($dest);
}
else
{
return false;
}
}
For me, the solution was to use ob_end_clean()
before outputting zip file contents (as noted by @Ywis in the comments)...
ob_end_clean();
readfile($zipfilename); // outputs zip file's content
... even if you don't output any characters before that.