How do I remove a directory that is not empty?

PhpDirectory

Php Problem Overview


I am trying to remove a directory with rmdir, but I received the 'Directory not empty' message, because it still has files in it.

What function can I use to remove a directory with all the files in it as well?

Php Solutions


Solution 1 - Php

There is no built-in function to do this, but see the comments at the bottom of <http://us3.php.net/rmdir>;. A number of commenters posted their own recursive directory deletion functions. You can take your pick from those.

Here's one that looks decent:

function deleteDirectory($dir) {
    if (!file_exists($dir)) {
        return true;
    }

    if (!is_dir($dir)) {
        return unlink($dir);
    }

    foreach (scandir($dir) as $item) {
        if ($item == '.' || $item == '..') {
            continue;
        }

        if (!deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
            return false;
        }

    }

    return rmdir($dir);
}

You could just invoke rm -rf if you want to keep things simple. That does make your script UNIX-only, so beware of that. If you go that route I would try something like:

function deleteDirectory($dir) {
    system('rm -rf -- ' . escapeshellarg($dir), $retval);
    return $retval == 0; // UNIX commands return zero on success
}

Solution 2 - Php

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);
 }
}

Solution 3 - Php

You could always try to use system commands.

If on linux use: rm -rf /dir If on windows use: rd c:\dir /S /Q

In the post above (John Kugelman) I suppose the PHP parser will optimize that scandir in the foreach but it just seems wrong to me to have the scandir in the foreach condition statement.
You could also just do two array_shift commands to remove the . and .. instead of always checking in the loop.

Solution 4 - Php

Can't think of an easier and more efficient way to do that than this

function removeDir($dirname) {
    if (is_dir($dirname)) {
        $dir = new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS);
        foreach (new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::CHILD_FIRST) as $object) {
            if ($object->isFile()) {
                unlink($object);
            } elseif($object->isDir()) {
                rmdir($object);
            } else {
                throw new Exception('Unknown object type: '. $object->getFileName());
            }
        }
        rmdir($dirname); // Now remove myfolder
    } else {
        throw new Exception('This is not a directory');
    }
}


removeDir('./myfolder');

Solution 5 - Php

My case had quite a few tricky directories (names containing special characters, deep nesting, etc) and hidden files that produced "Directory not empty" errors with other suggested solutions. Since a Unix-only solution was unacceptable, I tested until I arrived at the following solution (which worked well in my case):

function removeDirectory($path) {
	// The preg_replace is necessary in order to traverse certain types of folder paths (such as /dir/[[dir2]]/dir3.abc#/)
	// The {,.}* with GLOB_BRACE is necessary to pull all hidden files (have to remove or get "Directory not empty" errors)
	$files = glob(preg_replace('/(\*|\?|\[)/', '[$1]', $path).'/{,.}*', GLOB_BRACE);
	foreach ($files as $file) {
        if ($file == $path.'/.' || $file == $path.'/..') { continue; } // skip special dir entries
		is_dir($file) ? removeDirectory($file) : unlink($file);
	}
	rmdir($path);
	return;
}

Solution 6 - Php

Here what I used:

function emptyDir($dir) {
	if (is_dir($dir)) {
		$scn = scandir($dir);
		foreach ($scn as $files) {
			if ($files !== '.') {
				if ($files !== '..') {
					if (!is_dir($dir . '/' . $files)) {
						unlink($dir . '/' . $files);
					} else {
						emptyDir($dir . '/' . $files);
						rmdir($dir . '/' . $files);
					}
				}
			}
		}
	}
}

$dir = 'link/to/your/dir';
emptyDir($dir);
rmdir($dir);

Solution 7 - Php

From http://php.net/manual/en/function.rmdir.php#91797

Glob function doesn't return the hidden files, therefore scandir can be more useful, when trying to delete recursively a tree.

<?php 
public static function delTree($dir) { 
   $files = array_diff(scandir($dir), array('.','..')); 
    foreach ($files as $file) { 
      (is_dir("$dir/$file")) ? delTree("$dir/$file") : unlink("$dir/$file"); 
    } 
    return rmdir($dir); 
  } 
?>

Solution 8 - Php

Try the following handy function:

/**
 * Removes directory and its contents
 *
 * @param string $path Path to the directory.
 */
function _delete_dir($path) {
  if (!is_dir($path)) {
    throw new InvalidArgumentException("$path must be a directory");
  }
  if (substr($path, strlen($path) - 1, 1) != DIRECTORY_SEPARATOR) {
    $path .= DIRECTORY_SEPARATOR;
  }
  $files = glob($path . '*', GLOB_MARK);
  foreach ($files as $file) {
    if (is_dir($file)) {
      _delete_dir($file);
    } else {
      unlink($file);
    }
  }
  rmdir($path);
}

Solution 9 - Php

I didn't arrive to delete a folder because PHP said me it was not empty. But it was. The function by Naman was the good solution to complete mine. So this is what I use :

function emptyDir($dir) {
    if (is_dir($dir)) {
        $scn = scandir($dir);
        foreach ($scn as $files) {
            if ($files !== '.') {
                if ($files !== '..') {
                    if (!is_dir($dir . '/' . $files)) {
                        unlink($dir . '/' . $files);
                    } else {
                        emptyDir($dir . '/' . $files);
                        rmdir($dir . '/' . $files);
                    }
                }
            }
        }
    }
}

function deleteDir($dir) {

    foreach(glob($dir . '/' . '*') as $file) {
        if(is_dir($file)){


            deleteDir($file);
        } else {
        
          unlink($file);
        }
    }
    emptyDir($dir);
    rmdir($dir);
}

So, to delete a directory and recursively its content :

deleteDir($dir);

Solution 10 - Php

With this function, you will be able to delete any file or folder

function deleteDir($dirPath)
{
    if (!is_dir($dirPath)) {
        if (file_exists($dirPath) !== false) {
            unlink($dirPath);
        }
        return;
    }

    if ($dirPath[strlen($dirPath) - 1] != '/') {
        $dirPath .= '/';
    }

    $files = glob($dirPath . '*', GLOB_MARK);
    foreach ($files as $file) {
        if (is_dir($file)) {
            deleteDir($file);
        } else {
            unlink($file);
        }
    }

    rmdir($dirPath);
}

Solution 11 - Php

There are plenty of solutions already, still another possibility with less code using PHP arrow function:

function rrmdir(string $directory): bool
{
    array_map(fn (string $file) => is_dir($file) ? rrmdir($file) : unlink($file), glob($directory . '/' . '*'));

    return rmdir($directory);
}

Solution 12 - Php

function delTree($dir) { 
    $files = array_diff(scandir($dir), array('.','..')); 
     foreach ($files as $file) 
       (is_dir("$dir/$file")) ? delTree("$dir/$file") : @unlink("$dir/$file"); 
     return @rmdir($dir); 
} 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionzeckdudeView Question on Stackoverflow
Solution 1 - PhpJohn KugelmanView Answer on Stackoverflow
Solution 2 - PhpAbhayView Answer on Stackoverflow
Solution 3 - PhpAntonioCSView Answer on Stackoverflow
Solution 4 - PhpRainView Answer on Stackoverflow
Solution 5 - PhpBrandon ElliottView Answer on Stackoverflow
Solution 6 - PhpNamanView Answer on Stackoverflow
Solution 7 - PhpMykola VeryhaView Answer on Stackoverflow
Solution 8 - PhpkenorbView Answer on Stackoverflow
Solution 9 - PhpfrancoisVView Answer on Stackoverflow
Solution 10 - PhpAbdulRahman AlShamiriView Answer on Stackoverflow
Solution 11 - PhpThiago CordeiroView Answer on Stackoverflow
Solution 12 - PhpMounir BouzidiView Answer on Stackoverflow