Are there best practices for filtering and displaying specific file types from a directory in PHP?

When filtering and displaying specific file types from a directory in PHP, it is important to use functions like scandir() to read the contents of the directory and then filter the files based on their file extensions. This can be achieved by using functions like pathinfo() to extract the file extension and then checking if it matches the desired file type. Finally, the filtered files can be displayed using HTML or any other desired output format.

$dir = "path/to/directory";
$files = scandir($dir);

foreach($files as $file){
    $fileExt = pathinfo($file, PATHINFO_EXTENSION);
    
    if($file != "." && $file != ".." && in_array($fileExt, ['jpg', 'png', 'gif'])){
        echo "<img src='$dir/$file' alt='$file'>";
    }
}