I am using ziparchive to create a zip for some files and then need to download the file using the following code.
if(count($valid_files > 0)){
$zip = new ZipArchive();
$zip_name = "pixels.zip";
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){
$error .= "* Sorry ZIP creation failed at this time";
}
foreach($valid_files as $file){
$zip->addFile($file);
}
$zip->close();
if(file_exists($zip_name)){
// force to download the zip
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$zip_name.'"');
ob_clean();
flush();
readfile($zip_name);
//remove zip file from temp path
unlink($zip_name);
}
} else {
echo "No valid files to zip";
exit;
}
Assuming that $valid_files
contains an array with each element as the complete file path. The above code is expected to create a zip file containing the files but on the contrary once the download is initiated it keeps on downloading without any finishing size or maximum size. And in some cases even if the file is downloaded then when we try to unzip the file it gives an error as invalid file. Unable to figure out the issue any help is greatly appreciated.
The major reason for this was that there was huge zip file already existing in the same folder with the zip name I used to create a new zip thus due to some reason the new zip was not created and this old huge zip begined to download and as suggested by Marcelo in the comments the size was not mentioned thus downloading wasn't successful but things worked when in declared encoding as binary mentioned the size and changed the zip name or deleted the previous zip file.