Consider working with SPL's fileinfo and iterator classes (i.e. SplFileInfo
, DirectoryIterator
and FilterIterator
, CallbackFilterIterator
, etc) to build something a little more resilient.
Example:
$directoryIterator = new DirectoryIterator($directoryPath);
$imageFilter = function (SplFileInfo $splFileInfo) {
return preg_match(
'/^screenshot[0-9]{1,3}\.png$/',
$splFileInfo->getFilename()
) ? true : false;
}
$filteredImageIterator = new CallbackFilterIterator(
$directoryIterator,
$imageFilter
);
foreach($filteredImageIterator as $image) { /* your code */ }