tags:

views:

117

answers:

2

hey guys, i wonder what's the easiest way to delete a directory with all it's files in it?

i'm using rmdir(PATH . '/' . $value); to delete a folder. however if there are files inside of it, i simply can't delete it.

regards

+1  A: 

There are at least two options available nowdays.

  1. Before deleting the folder, delete all it's files and folders (and this means recursion!). Here is an example:

    public static function deleteDir($dirPath) {
        if (! is_dir($dirPath)) {
            throw new InvalidArgumentException('$dirPath must be a directory');
        }
        if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
            $dirPath .= '/';
        }
        $files = glob($dirPath . '*', GLOB_MARK);
        foreach ($files as $file) {
            if (is_dir($file)) {
                self::deleteDir($file);
            } else {
                unlink($file);
            }
        }
        rmdir($dirPath);
    }
    
  2. And if you are using 5.3 you can use a RecrusiveIterator to do it without recrusion, but it may not seem so simple:

    $it = new RecursiveDirectoryIterator(
              'samples' . DIRECTORY_SEPARATOR . 'sampledirtree');
    $files = new RecursiveIteratorIterator($it,
                 RecursiveIteratorIterator::CHILD_FIRST);
    foreach($files as $file){
        if ($file->isDir()){
            rmdir($file->getRealPath());
        } else {
            unlink($file->getRealPath());
        }
    }
    
alcuadrado
+1  A: 

what's the easiest way to delete a directory with all it's files in it?

system("rm -rf $dir");
Col. Shrapnel
I hope you're not serious. What happens if $dir is /
The Pixel Developer
@The exactly the same as with any of the codes above. Isn't it?
Col. Shrapnel