-3

Possible Duplicate:
A recursive remove directory function for PHP?

With PHP

I want to know the easiest way for delete a folder with files and folders inside.

Community
  • 1
  • 1
Yasmina Saraya
  • 95
  • 1
  • 1
  • 4

4 Answers4

2

This trick from the PHP docs is pretty cool:

function rrmdir($path)
{
  return is_file($path)?
    @unlink($path):
    array_map('rrmdir',glob($path.'/*'))==@rmdir($path)
  ;
}

It exploits array_map, which calls the given function on an array of results. It's also cross-platform.

Zach Rattner
  • 20,745
  • 9
  • 59
  • 82
1

system("rm -fr $foldername");

It only works on unix though, but it is easy.

Ariel
  • 25,995
  • 5
  • 59
  • 69
  • 1
    I do not recommend doing this, but if you must, please make sure you (a) use `escapeshellcmd` on `$foldername` before calling this, and (b) be careful of the path you're executing from. I'd make sure `$foldername` is an absolute path, just to be safe. – Zach Rattner Sep 26 '11 at 00:22
  • Thank you and have you in a way that is independent of the shell to Unix? – Yasmina Saraya Sep 26 '11 at 00:23
0

This recursive function has been posted as a comment on the rmdir() function reference page:

function rrmdir($dir) {
    if (is_dir($dir)) {
        $objects = scandir($dir);
        foreach ($objects as $object) {
            if ($object != "." && $object != "..") {
                if (filetype($dir . "/" . $object) == "dir")
                    rrmdir($dir . "/" . $object);
                else
                    unlink($dir . "/" . $object);
            }
        }
        reset($objects);
        rmdir($dir);
    }
}
RavuAlHemio
  • 2,331
  • 19
  • 22
0

This was posted here http://www.php.net/manual/en/function.rmdir.php

if(!file_exists($directory) || !is_dir($directory)) { 
    return false; 
} elseif(!is_readable($directory)) { 
    return false; 
} else { 
    $directoryHandle = opendir($directory); 

    while ($contents = readdir($directoryHandle)) { 
        if($contents != '.' && $contents != '..') { 
            $path = $directory . "/" . $contents; 

            if(is_dir($path)) { 
                deleteAll($path); 
            } else { 
                unlink($path); 
            } 
        } 
    } 

    closedir($directoryHandle); 

    if($empty == false) { 
        if(!rmdir($directory)) { 
            return false; 
        } 
    } 

    return true; 
} 

}

Mob
  • 10,958
  • 6
  • 41
  • 58