open('...">

RecursiveDirectoryIterator throws UnexpectedValueException to "Too many open files"

The following code:

$zip = new ZipArchive(); if ($zip->open('./archive.zip', ZIPARCHIVE::CREATE) !== TRUE) { die ("Could not open archive"); } $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("./folder/")); foreach ($iterator as $key => $value) { try { $zip->addFile(realpath($key), $key); echo "'$key' successfully added.\n"; } catch (Exception $e) { echo "ERROR: Could not add the file '$key': $e\n"; } } $zip->close(); 

Throws the following exception if there are too many files in the subfolder you are trying to iterate over:

 Uncaught exception 'UnexpectedValueException' with message 'RecursiveDirectoryIterator::__construct(./some/path/): failed to open dir: Too many open files' in /some/other/path/zip.php:24 Stack trace: #0 [internal function]: RecursiveDirectoryIterator->__construct('./some/path/') #1 /some/other/path/zip.php(24): RecursiveDirectoryIterator->getChildren() #2 {main} thrown in /some/other/path/zip.php on line 24 

How can you successfully iterate over a large number of folders and files without experiencing this exception?

+7
source share
1 answer

Just converting the iterator to an array using the iterator_to_array function, it looks like you can iterate over as many files as you want, d like it:

 $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("./folder/")); $files = iterator_to_array($iterator, true); // iterate over the directory // add each file found to the archive foreach ($files as $key => $value) { try { $zip->addFile(realpath($key), $key); echo "'$key' successfully added.\n"; } catch (Exception $e) { echo "ERROR: Could not add the file '$key': $e\n"; } } 
+7
source

All Articles