Skip to content
PHP Logo

How can one dynamically retrieve and display images from a folder in PHP?

To dynamically retrieve and display images from a folder in PHP, you can use the `scandir()` function to get a list of files in the directory, filter out only the image files, and then loop through the list to display each image.

php
<?php
$dir = 'images/'; // directory path
$files = array_diff(scandir($dir), array('..', '.')); // get list of files in directory
foreach($files as $file) {
    if (in_array(pathinfo($file, PATHINFO_EXTENSION), array('jpg', 'jpeg', 'png', 'gif'))) {
        echo '<img src="' . $dir . $file . '" alt="' . $file . '">';
    }
}
?>