Delete directory with files in it?

Delete directory with files in it?

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

Stefan Bogdanescu

Founder & Senior Architect

Why rmdir Fails and How to Actually Remove a Directory

When attempting to remove a directory in PHP, using rmdir() is often the first instinct because it matches the function name to the task. However, this approach hits an immediate wall: the function only succeeds if the target directory is empty. If you pass a path containing files or subdirectories to rmdir(), the operation fails silently or throws a warning depending on your error reporting level, leaving the folder intact and your script potentially in an inconsistent state.

The root cause lies in the design philosophy of POSIX-compliant file systems. The system distinguishes between removing a single entry (like a file) and removing a container (a directory). A standard rmdir call is strictly for empty containers. To clear a directory recursively, you need to either delete its contents first or use a function designed to handle the hierarchy.

In PHP, the built-in alternative is unlink() combined with scandir(), but this approach is brittle. It requires you to manually iterate through every file and subdirectory, handling permission errors for each item individually before attempting to delete the parent directory. If a single nested folder is read-only or owned by a different user, your loop breaks, and you end up with a partially deleted structure that still needs manual cleanup via the terminal.

A more robust solution involves using glob() or recursive iteration to gather all paths, then passing them to unlink(). However, even this method doesn't elegantly handle nested directories without explicit logic to recurse into subfolders first. This is where third-party libraries often shine by abstracting the recursion logic away from your core business code.

One of the most widely adopted solutions in the PHP ecosystem for this specific problem is the Filesystem facade provided by Laravel, or specifically the spatie/flysystem package which many frameworks utilize. While native functions exist, they require verbose boilerplate to handle edge cases like symbolic links or special permission bits.

If you are working within a Laravel application, the Storage facade offers a clean interface for this task:

use Illuminate\Support\Facades\Storage;

$directory = '/uploads/temp';

if (Storage::exists($directory)) {
    Storage::deleteDirectory($directory);
}

This method internally handles the recursive deletion of files and subdirectories. It also manages the underlying system calls to ensure the directory is truly empty before removing it from the file system metadata. The trade-off here is a slight overhead compared to raw system calls, but it significantly reduces the risk of leaving orphaned files behind due to permission errors or race conditions.

For non-Laravel projects or when you need direct control over the deletion process without external dependencies, the rrmdir approach using the glob() function is the native PHP equivalent. You can iterate through all items in the directory, delete files with unlink(), and recursively call a function on subdirectories. This pattern ensures that every item is processed before the parent directory is removed.

function recursiveDelete($path) {
    $files = glob("$path/*");
    
    foreach ($files as $file) {
        if (is_dir($file)) {
            // Recursively delete subdirectories
            recursiveDelete($file);
        } else {
            // Delete files
            unlink($file);
        }
    }
    
    // Finally, remove the now-empty directory
    rmdir($path);
}

recursiveDelete('/path/to/directory');

This implementation explicitly handles the distinction between files and directories. It ensures that rmdir() is only called after all children have been removed. A common pitfall to watch for is handling symbolic links; if a symlink points outside the target directory, standard globbing might behave unexpectedly depending on the PHP version and file system configuration.

Additionally, consider the security implications of such an operation. Deleting a directory often involves sensitive data. Ensure that the script running this code has the necessary permissions (usually chmod 755 or higher on the target folder) and that no concurrent processes are writing to the directory at the same time, which could lead to permission denied errors during the recursive removal process.

If your project is already built on top of a framework like Laravel, leveraging their existing storage abstraction layers is generally preferred over reinventing the wheel with native functions unless you have specific constraints requiring direct system access. For more information on file system operations within modern PHP frameworks, resources like https://laravelcompany.com often provide further insights into best practices for managing disk operations securely and efficiently.

Our network