I don’t understand why every time I run the following script, the zip file will contain all the previous files.
I want to start with an empty archive every time I run the script. How can I do that?
I tried adding an empty folder, but that does not help.
// open zip
$zip = new ZipArchive;
$zip->open($zipName, ZipArchive::CREATE);
// add pdfs to zip file
$zip->addEmptyDir('.'); // does not help
foreach($arPDFs as $thisPDF) {
if (File::exists(config('path')['scTemp'].$thisPDF)) {
$zip->addFile(config('path')['scTemp'].$thisPDF,$thisPDF);
}
}
// close zip
$zip->close();
// delete all pdfs
foreach($arPDFs as $thisPDF) {
if (File::exists(config('path')['scTemp'].$thisPDF)) {
File::delete(config('path')['scTemp'].$thisPDF);
}
}
// download zip file
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipName);
header('Content-Length: '.filesize($zipName));
readfile($zipName);
2
Answers
You need to ensure the previous zip file is deleted before creating a new one.
This is how zip works in general, if the file already exists, you modify it. Apart from what has been outlined in the answer by Karl Hill you can also open() it with the ZipArchive::OVERWRITE flag (second parameter after the filename).
This should better reflect your intention opening it.