Get all the images from a folder in PHP

In PHP, you can retrieve all images from a folder using the glob() function. This function searches for files matching a specific pattern and returns an array of matching file paths.

Using glob() with Single Extension

The simplest approach is to specify the folder path and file extension pattern −

<?php
$dir_name = "path/to/image/folder/";
$images = glob($dir_name."*.png");

foreach($images as $image) {
    echo '<img src="'.$image.'" /><br />';
}
?>

Getting Multiple Image Formats

To retrieve different image formats (PNG, JPG, GIF), you can use the GLOB_BRACE flag −

<?php
$dir_name = "images/";
$extensions = "*.{jpg,jpeg,png,gif,bmp}";
$images = glob($dir_name.$extensions, GLOB_BRACE);

foreach($images as $image) {
    echo '<img src="'.$image.'" alt="Image" style="max-width:200px;" /><br />';
}
?>

Using scandir() Alternative

You can also use scandir() with array_filter() for more control −

<?php
$dir_name = "images/";
$allowed_extensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp'];

$files = scandir($dir_name);
$images = array_filter($files, function($file) use ($allowed_extensions) {
    $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
    return in_array($extension, $allowed_extensions);
});

foreach($images as $image) {
    echo '<img src="'.$dir_name.$image.'" alt="Image" /><br />';
}
?>

Comparison

Method Advantages Use Case
glob() Simple, pattern matching Basic file filtering
scandir() More control, custom filtering Complex file validation

Conclusion

Use glob() for simple image retrieval with pattern matching, or scandir() when you need more control over file filtering. Both methods return file paths that can be used directly in HTML image tags.

Updated on: 2026-03-15T08:40:55+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements