What are the best practices for handling file extensions and filtering out non-image files when reading files from a directory in PHP?

When reading files from a directory in PHP, it's important to filter out non-image files by checking their file extensions. This can help prevent errors when processing the files and ensure that only image files are handled. One way to achieve this is by using the `pathinfo()` function to extract the file extension and then comparing it against a list of allowed image extensions.

$directory = '/path/to/directory';
$allowedExtensions = ['jpg', 'jpeg', 'png', 'gif'];

$files = scandir($directory);

foreach ($files as $file) {
    if (!in_array(pathinfo($file, PATHINFO_EXTENSION), $allowedExtensions)) {
        continue; // Skip non-image files
    }

    // Process image file here
}