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: // your filter logic $imageFilter = function (SplFileInfo $splFileInfo) { return preg_match( '/^screenshot[0-9]{1,3}\.png$/', $splFileInfo->getFilename() ) ? true : false; } // get files in directory based on filter function try { $directoryIterator = new DirectoryIterator($directoryPath); $filteredImageIterator = new CallbackFilterIterator( $directoryIterator, $imageFilter ); } catch (Exception $e) { // do something here, or don't wrap in try-catch at all if you want to bubble up exception. } foreach($filteredImageIterator as $image) { /* your code */ } Note that you can build upon the filter shown here by adding things like verifying file is readable/writable, get file modification timestamps, or other such functionality exposed by `SplFileInfo`, which could include ability to easily create `SplFileObject` for working with file contents.