Sling Academy
Home/PHP/PHP: List all images in a directory (ignoring other file types)

PHP: List all images in a directory (ignoring other file types)

Last updated: January 12, 2024

Introduction

When building web applications or managing content, you might find yourself in a situation where you need to list all the images within a directory, potentially for a gallery or a file manager. PHP, being a server-side scripting language, provides powerful functions to read directories and file information, making it a simple task to filter and list images. This article will guide you through a step-by-step process of listing all images in a directory using PHP while ignoring non-image file types.

In this tutorial, we’re only interested in image files, which commonly include file types such as ‘.jpg’, ‘.jpeg’, ‘.png’, ‘.gif’, and ‘.bmp’. We’ll see how to use PHP’s glob() function, pathinfo(), and file system iterator classes to effectively list images in a directory.

Prerequisites:

  • A basic understanding of PHP and how to run PHP scripts
  • Access to a PHP environment (version 5.3 or greater)
  • A directory containing image files and potentially other file types to test the script

Using glob() function

The glob() function is one of the easiest ways to search for files that match a specified pattern. You can use it to find all image files in a directory by only searching for files that have image-related extensions.

<?php
$images = glob('path/to/directory/*.{jpg,jpeg,png,gif,bmp}', GLOB_BRACE);
foreach ($images as $image) {
    echo '<img src="' . htmlspecialchars($image) . '" alt="Image" />';
}
?>

Make sure to replace ‘path/to/directory’ with the actual path to your images directory.

Using pathinfo()

The pathinfo() function can be used to retrieve information about a file path including the extension. You can loop through all files in a directory and use pathinfo() to filter out non-image files.

<?php
$directory = 'path/to/directory';
$files = scandir($directory);
foreach ($files as $file) {
    if (in_array(pathinfo($file, PATHINFO_EXTENSION), ['jpg', 'jpeg', 'png', 'gif', 'bmp'])) {
        echo '<img src="' . htmlspecialchars($directory . '/' . $file) . '" alt="Image" />';
    }
}
?>

File System Iterators

PHP’s FilesystemIterator and RegexIterator classes can provide an object-oriented way to filter and iterate through directory content. They are particularly useful if you’re dealing with a large number of files.

<?php
$directory = new FilesystemIterator('path/to/directory');
$filter = new RegexIterator($directory, '/\.(?:jpg|jpeg|png|gif|bmp)$/i', RegexIterator::MATCH);
foreach ($filter as $fileinfo) {
    if ($fileinfo->isFile()) {
        echo '<img src="' . htmlspecialchars($fileinfo->getPathname()) . '" alt="Image" />';
    }
}
?>

Conclusion

In conclusion, PHP provides multiple ways to list images in a directory and ignore other file types. Whether you prefer a functional approach with glob() and pathinfo(), or an object-oriented approach with the FilesystemIterator, you now have the tools and examples to list image files in any directory using PHP. By fine-tuning these methods, you can create a robust solution for managing and displaying image content on your application.

Next Article: PHP: How to create directories based on date (YYYY/MM/DD)

Previous Article: PHP: How to execute shell commands with shell_exec()

Series: PHP System & FIle I/O Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array