get all the images from a folder in php

get all the images from a folder in php

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Retrieving Image Filenames from a Directory in PHP

Retrieving a list of image files from a specific directory is a common requirement when building media galleries, asset scanners, or dynamic thumbnail generators. In the context of a WordPress theme located at mytheme/images/myimages, you need to interact with the filesystem directly to scan the folder without relying on database queries. The most robust approach involves using PHP's standard scandir() function in combination with pathinfo() or glob().

While scandir() returns all entries—including subdirectories—you must filter the results to ensure you are only processing files, and specifically those with image extensions. A naive implementation might list folders as images or fail to handle hidden files correctly if not configured properly. The following example demonstrates a clean method using scandir with GLOB_BRACE logic simulated via filtering, which offers better control over extension validation.

$folderPath = 'mytheme/images/myimages';

// Ensure the path is absolute to avoid issues relative to current execution context
if (!is_dir($folderPath)) {
    throw new InvalidArgumentException("The target directory does not exist.");
}

$extensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'];
$imageFiles = [];

// scandir returns entries including '.', '..' and hidden files
$entries = scandir($folderPath);

foreach ($entries as $entry) {
    // Skip directory entries and current/parent references
    if (is_dir($folderPath . '/' . $entry)) {
        continue;
    }

    $fileExtension = strtolower(pathinfo($entry, PATHINFO_EXTENSION));

    // Only process files with known image extensions
    if (in_array($fileExtension, $extensions, true)) {
        $imageFiles[] = $folderPath . '/' . $entry;
    }
}

This code snippet provides a full list of absolute paths to valid image files. If you only need the filenames without the directory path, you can store just $entry in the array instead. Using pathinfo() to extract the extension is generally safer than using regular expressions, as it handles edge cases like hidden extensions (e.g., .jpg.backup) more gracefully by strictly parsing the last dot-separated segment.

An alternative approach utilizes glob() with a specific pattern string. This method allows you to define the directory and the file pattern in a single function call, which can be slightly more concise if your folder structure is predictable.

$folderPath = 'mytheme/images/myimages';
$pattern = $folderPath . '/*.{jpg,jpeg,png,gif,webp,svg}';

// Note: Glob patterns with multiple extensions often require GLOB_BRACE flag on older PHP versions
$flags = defined('GLOB_BRACE') ? GLOB_BRACE : 0;

$imageFiles = glob($pattern, $flags);

When choosing between scandir and glob, consider the performance implications if you are scanning thousands of files. scandir reads the directory listing into memory at once, whereas glob behaves similarly but offers better syntax for complex inclusion/exclusion rules. However, scandir remains the preferred choice in WordPress core for its reliability across different server configurations and PHP versions.

A critical pitfall to avoid is assuming that a file with an .jpg extension is actually a valid image. File extensions are not guaranteed indicators of file type. If your application requires strict validation, you should check the MIME type using finfo_file() rather than relying solely on the filename. This prevents serving binary executables or corrupted files as images in your theme gallery.

For more complex needs involving directory recursion or specific file size limits, you might consider leveraging a package like league/flysystem if you plan to move toward an object storage abstraction later. Until then, sticking to built-in functions ensures maximum compatibility within the WordPress environment without introducing unnecessary dependencies.

Our network