我不明白为什么每次运行以下脚本时,zip 文件都会包含以前的所有文件。
我想每次运行脚本时都从一个空的存档开始。我怎样才能做到这一点?
我尝试添加一个空文件夹,但这没有帮助。
// 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);
您需要确保在创建新的 zip 文件之前删除之前的 zip 文件。
use Illuminate\Support\Facades\File;
// Define the zip file name
$zipName = 'new_archive.zip';
// Check if the previous zip file exists and delete it
if (File::exists($zipName)) {
File::delete($zipName);
}
// Create a new zip archive
$zip = new ZipArchive;
$zip->open($zipName, ZipArchive::CREATE);
// Add pdfs to the zip file
foreach ($arPDFs as $thisPDF) {
if (File::exists(config('path')['scTemp'] . $thisPDF)) {
$zip->addFile(config('path')['scTemp'] . $thisPDF, $thisPDF);
}
}
// Close the zip archive
$zip->close();
// Download the zip file
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename=' . $zipName);
header('Content-Length: ' . filesize($zipName));
readfile($zipName);