skip to Main Content

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


  1. You need to ensure the previous zip file is deleted before creating a new one.

    use IlluminateSupportFacadesFile; 
    
    // 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);
    
    Login or Signup to reply.
  2. 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).

    $zip->open($zipName, ZipArchive::CREATE | ZipArchive::OVERWRITE)
      || throw new Error("Unable to open the Zip archive!");
    

    This should better reflect your intention opening it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search