How do I recursively delete a directory and its entire contents (files + sub dirs) in PHP?

How do I recursively delete a directory and its entire contents (files + sub dirs) in PHP?

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

Stefan Bogdanescu

Founder & Senior Architect

The Perils of Recursive Directory Removal in PHP

Deleting a single file or an empty directory in PHP is trivial: unlink() for files and rmdir() for empty folders. However, removing a directory that contains nested subdirectories and files requires a different approach because the underlying filesystem enforces a strict order of operations. You cannot delete a parent directory until its contents are gone, and you often cannot delete a subdirectory until it is empty. Attempting to pass a non-empty path directly to rmdir() will fail with an error code, leaving your cleanup script stuck in a partial state.

The most common mistake developers make is assuming that a single function call can handle the complexity of nested structures. While some systems provide utilities like rm -rf on Unix-like environments or the Windows rd /s /q command, relying on shell commands from within PHP introduces security vulnerabilities and portability issues. It is generally safer to implement the deletion logic in pure PHP or use well-tested extensions that abstract this complexity.

The Iterative Approach with exec()

One pragmatic solution involves using the operating system's native capabilities via a simple one-liner executed through PHP's exec() or shell_exec() functions. For Linux and macOS, the command is straightforward:

$command = "rm -rf {$directoryPath}";
exec($command, $output, $returnCode);

This method effectively bypasses the need to write a complex recursive loop yourself. The rm utility with the -r (recursive) and -f (force) flags handles all nested levels. However, this approach has significant drawbacks in a production environment. Passing user input directly into shell commands creates an immediate risk of command injection attacks. Additionally, relying on the OS shell makes your code dependent on specific Unix utilities, rendering it incompatible with Windows servers unless you switch to rmdir /s or PowerShell commands, which complicates cross-platform deployment.

Implementing a Pure PHP Solution

For maximum portability and security control, implementing a recursive deletion function in pure PHP is often the preferred strategy. This method gives you granular control over what gets deleted and allows for better error handling without relying on external binaries.

The logic follows a depth-first traversal pattern: first, iterate through the directory's contents; then, delete each item individually; finally, remove the empty directory itself. Here is a robust implementation using standard PHP functions:

function recursiveDelete(string $directory): bool
{
    if (!is_dir($directory)) {
        return false;
    }

    // Use the FilesystemIterator to handle symbolic links safely
    $items = new FilesystemIterator($directory, FilesystemIterator::SKIP_DOTS);

    foreach ($items as $item) {
        $relativePath = $item->getPathname();

        if ($item->isDir()) {
            // Recursively delete subdirectories first
            recursiveDelete($directory . '/' . $item->getBasename());
        } else {
            // Delete files directly
            unlink($relativePath);
        }
    }

    // Once the directory is empty, remove it
    return rmdir($directory);
}

This function explicitly skips the current directory itself (SKIP_DOTS) to avoid infinite recursion. It processes subdirectories recursively before attempting to delete files or the parent folder. This ensures that when rmdir() is finally called, the target path is guaranteed to be empty, preventing "Directory not empty" exceptions.

Trade-offs and Security Considerations

While the pure PHP approach works well for most scenarios, it does come with performance trade-offs compared to native shell commands. Iterating through thousands of files in a loop can consume significant memory and CPU time. If you are dealing with massive directories containing millions of files, consider using extensions like php-swoole or optimizing your iterator logic to handle batches more efficiently.

Furthermore, always validate the directory path before execution. Never trust user input blindly; sanitize paths to prevent traversal attacks (e.g., deleting /etc/passwd by targeting a symlink named ../etc/passwd). The FilesystemIterator class is particularly useful here as it handles symbolic links gracefully based on the flags you pass, allowing you to decide whether to follow them or treat them as regular entries.

If your application stack includes Laravel, leveraging their built-in file system helpers can simplify this process. The framework provides a clean API for interacting with the filesystem that abstracts away many of these low-level details, ensuring consistent behavior across different environments while maintaining security best practices.

Our network