Best way to get files from a dir filtered by certain extension in php

Best way to get files from a dir filtered by certain extension in php

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

Stefan Bogdanescu

Founder & Senior Architect

Filtering Files by Extension in PHP: A Practical Approach

When you run scandir() on a directory, it returns every entry in that folder, including hidden files and dot-files. The function is fast because it relies on the operating system's file system APIs to read the directory entries directly. However, if your goal is to process only specific file types—say, configuration files ending in .ini or image assets with .jpg, .png, or .gif extensions—you need to filter those results programmatically.

The most straightforward and efficient way to do this without sacrificing performance is to use scandir() for the initial scan and then apply a simple filter in PHP. This approach avoids unnecessary system calls, which would be significantly slower if you were to iterate through files one by one using glob() or multiple opendir()/readdir() loops.

Here is how you can structure the logic:

$dir_f = "whatever/random/";
$extensions = ['ini', 'jpg', 'png', 'gif']; // Define your target extensions

$files = scandir($dir_f);

// Filter out non-files and unwanted extensions
$fileList = array_filter($files, function ($file) use ($extensions) {
    // scandir returns '.' and '..' as the first two elements
    if ($file === '.' || $file === '..') {
        return false;
    }

    // Ensure it's a regular file and not a directory
    if (!is_file($dir_f . DIRECTORY_SEPARATOR . $file)) {
        return false;
    }

    // Extract the extension and compare (case-insensitive usually preferred)
    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
    
    return in_array($ext, $extensions, true);
});

// array_filter returns an array with null keys by default. 
// If you need associative indices:
$fileList = array_values($fileList);

This pattern is robust because it separates the concerns of directory traversal and content filtering. The scandir call is a single system operation, while the array_filter handles the logic in memory. Since arrays are already loaded into PHP's memory after scandir, iterating over them is extremely fast compared to making additional filesystem calls.

One common pitfall developers encounter is handling directory entries returned by scandir. The function includes . and .. in its output, which refer to the current and parent directories respectively. These are not files, so they must be explicitly excluded from your list before attempting to process them. Failing to check for these can lead to errors when trying to open or read those paths as regular files.

Another consideration is case sensitivity. On Linux systems, file extensions are often lowercase, but on Windows or macOS (depending on settings), they might appear in mixed case. Using strtolower() ensures that your filtering logic works consistently regardless of the operating system's default behavior.

If you are working within a Laravel application, the built-in filesystem helper provides an alternative approach using Files::allFiles($directory) combined with filtering, or leveraging Laravel's event-driven file handling if you need to react to specific file changes. However, for raw performance and simplicity in standard PHP scripts, the scandir + array_filter combination remains the most efficient solution.

There are scenarios where you might prefer glob() with a pattern like *.ini, but glob can be slower when dealing with large directories because it may perform multiple filesystem reads depending on implementation details. Stick to scandir for bulk operations unless you specifically need wildcard matching capabilities that cannot be easily simulated in PHP code.

Ultimately, the choice depends on your specific constraints. If performance is critical and the directory size varies widely, always benchmark both approaches in your environment. But in most cases, filtering a single scandir result set is the optimal balance between readability and speed.

Our network