PHP

Recursively Delete Directory

admin by @admin ADMIN
5h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Remove a directory and everything under it. Defensive against symlinks (unlinks the symlink rather than recursing into it). Returns the count of items removed.
PHP
Raw
<?php
function rmrf(string $path): int {
    if (!file_exists($path)) return 0;
    if (is_link($path) || !is_dir($path)) {
        return unlink($path) ? 1 : 0;
    }
    $count = 0;
    foreach (scandir($path) as $entry) {
        if ($entry === '.' || $entry === '..') continue;
        $count += rmrf($path . DIRECTORY_SEPARATOR . $entry);
    }
    rmdir($path);
    return $count + 1;
}

$removed = rmrf('/tmp/build-cache');
echo "Removed $removed items\n";
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.