How can PHP scripts efficiently handle large numbers of image files in a directory to prevent performance issues related to filesystem I/O operations?

When dealing with a large number of image files in a directory, it is important to minimize filesystem I/O operations to prevent performance issues. One way to efficiently handle this is by using caching mechanisms to store file information in memory and reduce the number of times the filesystem needs to be accessed.

// Use caching to store file information in memory
$cache = [];

// Function to get file information with caching
function getFileInformation($filename) {
    global $cache;
    
    if (!isset($cache[$filename])) {
        $cache[$filename] = file_exists($filename) ? stat($filename) : false;
    }
    
    return $cache[$filename];
}

// Example usage
$files = glob('/path/to/directory/*.jpg');
foreach ($files as $file) {
    $info = getFileInformation($file);
    if ($info) {
        // Process file information
    }
}