What are the advantages of using a whitelist approach with pathinfo to filter out non-image files when working with directories in PHP?

When working with directories in PHP, it is important to filter out non-image files to ensure that only valid image files are processed. One way to do this is by using a whitelist approach with pathinfo, which allows you to extract information about a file path and determine its file extension. By checking the file extension against a list of allowed image extensions, you can effectively filter out non-image files and only process the desired image files.

$allowedExtensions = array('jpg', 'jpeg', 'png', 'gif');

$files = glob('path/to/directory/*');
foreach ($files as $file) {
    $fileInfo = pathinfo($file);
    if (in_array(strtolower($fileInfo['extension']), $allowedExtensions)) {
        // Process the image file
    }
}