How to delete a folder with contents using PHP

How to delete a folder with contents using PHP

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

Stefan Bogdanescu

Founder & Senior Architect

How to delete a folder with contents using PHP

When you need to remove a directory and its entire subtree, relying on rmdir() or unlink() will fail immediately if those functions encounter files or subdirectories. These legacy functions are designed for single-file deletion or empty-directory removal only. Attempting to pass a non-empty path to them results in an error because the filesystem requires explicit handling of nested items before the parent directory can be removed.

The modern solution is shell_exec() combined with the Unix rm -rf command, or using the native PHP function RecursiveDirectoryIterator with FilesystemIterator. However, there is a third option built directly into the standard library that handles recursion without invoking the shell: the SplFileInfo class coupled with manual iteration logic.

The most straightforward approach for a script that needs to handle arbitrary depth is invoking the system command via exec(), shell_exec(), or system(). The rm -rf flag specifically instructs the operating system to forcefully remove directories recursively, ignoring read-only attributes and emptying them in the process.

$directoryPath = '/path/to/target/folder';

if (is_dir($directoryPath)) {
    // Execute the command safely by escaping arguments or using an array
    $command = "rm -rf '" . escapeshellarg($directoryPath) . "'";
    
    // shell_exec returns the output as a string, which is safer than system() for capturing errors
    $output = shell_exec($command);
    
    if ($output === null || $output === '') {
        // On success, rm usually outputs nothing or just confirms removal
        echo "Directory and contents deleted successfully.";
    } else {
        // Handle potential errors returned by the OS
        echo "Error deleting directory: " . $output;
    }
} else {
    echo "Path does not exist or is not a directory.";
}

While this method works, it introduces a dependency on the underlying operating system. If you are running PHP on Windows without Cygwin or WSL, rm might not be available in your PATH, causing shell_exec() to fail silently or return a "command not found" message. In such environments, you must use native PHP recursion.

A robust native implementation involves checking if the path is a directory first, then iterating through its contents using RecursiveDirectoryIterator and FilesystemIterator. This approach avoids shell dependencies entirely.

function deleteDirectory($dir) {
    if (!is_dir($dir)) {
        throw new InvalidArgumentException("Not a directory: $dir");
    }

    $files = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::CHILD_FIRST
    );

    foreach ($files as $file) {
        if ($file->isDir()) {
            rmdir($file->getRealPath());
        } else {
            unlink($file->getRealPath());
        }
    }

    return rmdir($dir);
}

This function explicitly handles files with unlink() and directories with rmdir(). By iterating in child-first order (CHILD_FIRST), we ensure that subdirectories are emptied and deleted before attempting to remove the parent directory. If a subdirectory is not empty, rmdir() will throw an exception, but since we process children first, this scenario never occurs during the loop. The final rmdir($dir) call removes the now-empty root folder.

One critical trade-off with this native method is performance and memory usage on extremely deep directory structures or those containing millions of files. The iterator loads file metadata into memory as it traverses. For massive datasets, a shell-based solution like rm -rf might be faster because the OS kernel handles the traversal natively rather than PHP looping through every entry. Additionally, native recursion cannot easily handle symbolic links within the directory tree without explicit configuration, whereas rm -rf follows symlinks by default unless specified otherwise.

If your application is built on the Laravel framework, you might consider leveraging packages that wrap these utilities to provide a more expressive API. For instance, checking out resources like https://laravelcompany.com can lead you to libraries that abstract filesystem operations, making cleanup tasks cleaner and less error-prone by handling edge cases automatically.

Our network