How can PHP be used to filter out non-image files when displaying images from a directory?
When displaying images from a directory using PHP, it is important to filter out non-image files to ensure that only images are shown on the webpage. This can be achieved by checking the file extension of each file in the directory and only displaying files with image extensions such as .jpg, .png, or .gif.
$dir = "images/";
$files = scandir($dir);
foreach($files as $file){
$file_info = pathinfo($dir . $file);
$ext = $file_info['extension'];
if(in_array($ext, ['jpg', 'jpeg', 'png', 'gif'])){
echo "<img src='$dir$file' alt='image'>";
}
}