solvit.io

Delete a non-empty directory recursively with PHP

Solution
public function removeDir($dirPath)
{
    if (!is_dir($dirPath)) {
        return;
    }

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

    foreach ($files as $file) {
        $file->isDir() ? rmdir($file->getRealPath()) : unlink($file->getRealPath());
    }
}
Example
function removeDir($dirPath) {
    // ...
}

removeDir('/tmp/output');
Find more solutions about: ,