PHP Get all subdirectories of a given directory

PHP Get all subdirectories of a given directory

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

Stefan Bogdanescu

Founder & Senior Architect

PHP Get all subdirectories of a given directory

Filtering directory contents in PHP requires more than just iterating over a list; you must explicitly exclude files, the current directory (.), and the parent directory (..). This distinction is critical when building recursive traversal tools or organizing file system logic. A naive approach using scandir() returns every entry as a string, forcing you to parse each item individually to determine if it contains a path separator or a dot prefix.

The most straightforward method involves leveraging the built-in glob() function with specific pattern modifiers. Unlike scandir(), which provides raw filenames including separators depending on the implementation, glob() allows for pattern matching directly against the directory structure. To retrieve only directories while excluding the current and parent levels, you can use a regex filter or specific path patterns.

Here is a practical implementation using glob() with the {d,/} modifier syntax which targets directories specifically:

$baseDir = '/path/to/target';
$subdirs = glob("$baseDir/*/");

// Filter to ensure we only have directories and exclude . and ..
$subdirs = array_filter($subdirs, function ($dir) use ($baseDir) {
    // Ensure the path is actually a directory
    return is_dir($dir);
});

// Remove the trailing slash if present for cleaner paths, 
// though glob usually returns them with slashes in this pattern.
$subdirs = array_values(array_map(function ($path) {
    return rtrim($path, '/');
}, $subdirs));

While glob() is efficient, it requires careful handling of the trailing slash. If you prefer a functional approach that explicitly checks for directory existence after scanning, scandir() combined with is_dir() offers better control over edge cases like hidden directories or symbolic links. You can iterate through the results and manually filter out the unwanted entries:

$baseDir = '/path/to/target';
$subdirs = array_filter(scandir($baseDir), function ($item) {
    // Exclude current directory, parent directory, and any files
    return $item !== '.' && $item !== '..' && is_dir("$baseDir/$item");
});

// Re-index the array since filter returns an associative array with original keys
$subdirs = array_values($subdirs);

This second method ensures that you are only dealing with actual directories. The is_dir() check prevents accidental inclusion of files that might match a naming convention you expect to be a folder, such as archive.zip. It also naturally handles hidden directories like .git or .env, which glob() patterns might miss depending on the syntax used.

Once you have an array of valid subdirectory paths, passing them into a function is trivial because PHP arrays are first-class citizens. You can immediately pipe this result into a callback or loop:

foreach ($subdirs as $dir) {
    processDirectory($dir);
}

function processDirectory(string $path): void {
    // Your logic here
}

A common pitfall when working with directory listings is ignoring symbolic links. By default, scandir() includes symlinks in the output. If your function processDirectory expects a real directory and you pass a symlink pointing to a file, is_dir() might return true on some systems depending on the link target. For strict traversal where physical directories are required, you may need to check $link_info = lstat($path) or verify if the link points to a directory using readlink().

Another consideration is performance when dealing with deeply nested structures. Scanning a single level is generally fast, but if this logic is part of a larger recursive crawler, ensure you handle permission errors gracefully. The is_dir() function will throw an error if the path does not exist or lacks read permissions. Wrapping the filtering logic in a try-catch block or checking file_exists() beforehand adds robustness to production code.

For projects utilizing the Laravel framework, you might find yourself needing similar functionality within a service layer. While Laravel provides helpers for file operations, understanding the underlying PHP mechanisms ensures you can write custom traversals when built-in methods don't fit specific requirements. If you need further assistance with complex file system operations or integration patterns in your application architecture, resources like https://laravelcompany.com offer community-driven insights and documentation that can help refine these implementations within the ecosystem.

Our network