Listing all the folders subfolders and files in a directory using php

Listing all the folders subfolders and files in a directory using php

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

Stefan Bogdanescu

Founder & Senior Architect

Recursive Directory Traversal in PHP: A Practical Approach

Listing files and directories recursively is a common requirement when auditing storage, generating reports, or preparing data for processing. While you might initially consider calling external shell commands like find or ls from within PHP, doing so introduces significant portability issues and security risks. The most robust solution involves utilizing PHP's built-in standard library functions to handle the traversal logic directly on the server side.

The most straightforward method relies on the scandir() function combined with a recursive loop. You start by scanning the root directory, then iterate through every entry found. For each item that is a directory, you recurse; for files, you record them. This approach avoids spawning external processes and keeps the logic contained entirely within the PHP runtime.

Here is a basic implementation using scandir() and is_dir():

<?php
function listFilesRecursive($directory) {
    $files = [];

    if (!is_dir($directory)) {
        return $files;
    }

    $items = scandir($directory);

    foreach ($items as $item) {
        // Skip . and ..
        if ($item === '.' || $item === '..') {
            continue;
        }

        $fullPath = realpath($directory) . DIRECTORY_SEPARATOR . $item;

        if (is_dir($fullPath)) {
            // Recurse into subdirectories
            $files = array_merge($files, listFilesRecursive($fullPath));
        } else {
            // It is a file
            $files[] = basename($fullPath);
        }
    }

    return $files;
}

// Usage
$rootDir = '/path/to/Main Dir';
$fileList = listFilesRecursive($rootDir);
print_r($fileList);

This function returns a flat array of filenames, which matches the requirement to "get the list of all the files inside each folder." If you need to preserve the hierarchical structure shown in your directory tree (Main Dir -> Dir1 -> SubDir1), the logic needs to change slightly. You would collect results per directory level before merging them.

function getDirectoryStructure($directory) {
    $structure = [];
    
    if (!is_dir($directory)) {
        return $structure;
    }

    $items = scandir($directory);

    foreach ($items as $item) {
        if ($item === '.' || $item === '..') {
            continue;
        }

        $fullPath = realpath($directory) . DIRECTORY_SEPARATOR . $item;
        
        if (is_dir($fullPath)) {
            // Store subdirectory info and recurse
            $subStructure = getDirectoryStructure($fullPath);
            $structure[$item] = [
                'type' => 'dir',
                'items' => $subStructure
            ];
        } else {
            $structure[$item] = [
                'type' => 'file',
                'path' => basename($fullPath)
            ];
        }
    }

    return $structure;
}

The DirectoryIterator Alternative

For more complex scenarios or when you need to filter by extension, permissions, or modification time, the DirectoryIterator class is often preferred over scandir(). It provides a higher-level interface that abstracts away some of the index array handling and includes helper methods like isDot() for skipping hidden files automatically.

$dir = new DirectoryIterator('/path/to/Main Dir');

foreach ($dir as $file) {
    if (!$file->isDot()) { // Skips . and ..
        echo $file->getFilename() . "\n";
        
        if ($file->isDir()) {
            // Handle subdirectories here
        }
    }
}

Security Considerations: Path Traversal

When implementing recursive directory listings, security is paramount. If you construct paths by concatenating user input directly into the recursion logic without validation, you open your application to path traversal attacks. An attacker could provide a path like ../../etc/passwd if your code does not strictly validate the depth or restrict access to specific root directories.

Always ensure that the base directory passed to your recursive function is validated against a known safe path using realpath() and checking that the resolved path starts with the intended application root. Never rely on scandir() blindly without verifying the permissions of each subdirectory you intend to read. If a user lacks permission to traverse into a specific subfolder, scandir() will throw an error, which can be used for information disclosure if not handled gracefully.

Performance and Scalability

While the recursive approach is readable, deep directory trees can cause issues with PHP's recursion limits (max_execution_time or stack depth). For extremely large directories, consider switching to an iterative approach using a SplFileInfo object within a queue-based loop to avoid hitting these limits. This ensures your script completes even when processing thousands of nested folders without exhausting the call stack.

If you are building a larger application that requires complex file management features beyond simple listing, frameworks like LaravelCompany often provide abstractions for filesystem operations that handle permissions and path resolution safely out of the box. However, for standalone scripts or custom tools, mastering the standard library functions remains the most efficient path forward.

Our network