0

I am trying to pack around 50 files from a folder to zip file using PHP ZipArchive. Actually, only at most five files are ever changing. Others remain same static files. Should I zip the folder for every request or just replace those five files. Which one would be better for memory consumption and performance?

<?php
    $zip = new ZipArchive();
    $zip->open('example.zip',  ZipArchive::CREATE);
    $srcDir = "/folderTobeZipped/";
    $files= scandir($srcDir);
    unset($files[0],$files[1]);
    foreach ($files as $file) {
        $zip->addFile("{$file}");    
    }
    $zip->close();
?>
Yesudass Moses
  • 1,841
  • 3
  • 27
  • 63
  • 2
    Obviously, if you are sure that they will always remain the same, it is better to leave them inside without adding them :) – Simone Rossaini Jul 29 '21 at 05:59
  • 1
    However, I recommend that you post this question in [codereview](https://codereview.stackexchange.com/) where they will help you improve the code. Here we fix the problems – Simone Rossaini Jul 29 '21 at 06:00

1 Answers1

0

To put it simply, avoiding extra processing whenever possible is always better for performance. You can only add files that changed - calculate a crc hash from each file like so:

$crcfromFile=hexdec(hash_file('crc32b',$fileName));

Zip archive stores the same crc for each file by default - you can get it like so:

$crcFromArchive=$zip->statName($fileName)['crc'];

Then you can compare both and take different action:

if($crcfromFile != $crcFromArchive)
//replace the file
else
//continue to the next file
Ziarek
  • 679
  • 6
  • 14