How can one optimize PHP scripts to handle larger files when creating Zip archives?

When creating Zip archives with PHP, handling larger files can lead to memory exhaustion or execution time limits being exceeded. To optimize PHP scripts for handling larger files when creating Zip archives, it is recommended to use streaming to read and write files in chunks rather than loading the entire file into memory at once.

// Create a zip archive and add files using streaming to handle larger files
$zip = new ZipArchive();
$zipFileName = 'archive.zip';
$zip->open($zipFileName, ZipArchive::CREATE);

$files = ['file1.txt', 'file2.txt', 'largefile.zip'];

foreach ($files as $file) {
    $handle = fopen($file, 'rb');
    if ($handle) {
        while (($buffer = fread($handle, 2048)) !== false) {
            $zip->addFromString(basename($file), $buffer);
        }
        fclose($handle);
    }
}

$zip->close();