Remove all files, folders and their subfolders with php

Remove all files, folders and their subfolders with php

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

Stefan Bogdanescu

Founder & Senior Architect

Remove all files, folders and their subfolders with php

You are likely encountering a classic edge case in file system management: the directory is not empty because it contains symbolic links to itself or its descendants. The recursive deletion script you found relies on opendir() and readdir() to list contents before attempting to remove parent directories with rmdir(). However, rmdir() fails if the target path exists but is not empty, or in specific scenarios involving symlinks depending on the OS file system implementation.

The output you observed—paths like /home/***/public_html/prestashop/img/p/3 failing to delete even with 777 permissions—strongly suggests a circular reference issue. This often happens when a symbolic link points to a parent directory or a child directory within the same tree. For example, if a folder named p contains a symlink named link-to-p that points back to /home/***/public_html/prestashop/img/p, the standard recursive logic gets stuck. The script lists the link as a file (or directory depending on the flag), fails to delete it cleanly because the target exists, and consequently cannot empty the parent folder p to allow rmdir() to succeed.

When testing with Prestashop unpacked archives, this is particularly common if the archive structure included symlinks or if the extraction process created hard links that confuse the directory traversal logic. Changing permissions from 755 to 777 does not resolve this because the issue is structural, not permission-based. The rmdir() system call will refuse to remove a directory that still holds entries in its inode table, and symbolic links pointing into the directory being deleted count as such entries.

To robustly handle this, you need a script that explicitly handles symbolic links before attempting to remove directories. Instead of blindly recursing, check if an entry is a symlink first. If it is, use unlink() to delete the link itself, regardless of where it points. Only after ensuring no symlinks remain should you attempt to recurse into subdirectories or unlink regular files.

Here is a refined approach that addresses the specific failure mode seen in your Prestashop test case:

function deleteDirectory($dir) {
    $files = array_diff(scandir($dir), array('.', '..'));
    
    foreach ($files as $file) {
        $path = $dir . DIRECTORY_SEPARATOR . $file;
        
        // Handle symbolic links first to break circular references
        if (is_link($path)) {
            @unlink($path);
        } elseif (is_dir($path, true)) {
            // Recursively delete subdirectories
            deleteDirectory($path);
        } else {
            // Delete regular files
            @unlink($path);
        }
    }

    // Remove the directory itself only if it is empty now
    return @rmdir($dir);
}

The critical change here is the use of is_link() before checking is_dir(). On many systems, especially Linux, a symbolic link to a directory is reported as a directory by is_dir(), but scandir() or readdir() might return it differently depending on how you iterate. By explicitly checking for links first and unlinking them immediately, you ensure the target of the link (even if it's the parent directory itself) does not prevent the current directory from being emptied.

Additionally, using scandir() with the GLOB_BRACE option or simply filtering . and .. is more reliable than manually appending slashes to paths passed to readdir(). The provided snippet uses @rmdir() to suppress warnings if a single file fails to delete, but in production environments, you might want to throw an exception or log specific errors rather than silently succeeding.

If you are working within the Laravel ecosystem and need similar functionality for cleaning up temporary storage or migration artifacts, Laravel provides utilities that abstract these filesystem operations. Specifically, the Storage facade often handles disk management more safely, though writing a custom recursive function gives you precise control over error handling strategies. For instance, wrapping the deletion logic in a try-catch block can prevent your entire script from crashing if a single stubborn file blocks the process.

When dealing with large archives like Prestashop, ensure your web server user (e.g., www-data) has write permissions on the target directory before calling the function, and be aware that deleting directories while serving them via a web server can lead to race conditions or 403/500 errors if not handled carefully. Always test deletion logic on a non-production environment first, as recursive removals are destructive by nature.

Our network