33

The rmdir() function fails if the folder contains any files. I can loop through all of the the files in the directory with something like this:

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

Is there any way to just delete it all at once?

Sam
  • 7,252
  • 16
  • 46
  • 65
Chris B
  • 15,524
  • 5
  • 33
  • 40

7 Answers7

63

rrmdir() -- recursively delete directories:

function rrmdir($dir) { 
  foreach(glob($dir . '/*') as $file) { 
    if(is_dir($file)) rrmdir($file); else unlink($file); 
  } rmdir($dir); 
}
Pragnesh Chauhan
  • 8,363
  • 9
  • 42
  • 53
Yuriy
  • 631
  • 5
  • 2
47

Well, there's always

system('/bin/rm -rf ' . escapeshellarg($dir));

where available.

chaos
  • 122,029
  • 33
  • 303
  • 309
3
function delete_files($dir) {
  if (is_dir($dir)) {
    $objects = scandir($dir);
    foreach ($objects as $object) {
      if ($object != "." && $object != "..") {
        if (filetype($dir."/".$object) == "dir") 
           delete_files($dir."/".$object); 
        else unlink   ($dir."/".$object);
      }
    }
    reset($objects);
    rmdir($dir);
  }
 }
GIPSSTAR
  • 2,050
  • 1
  • 25
  • 20
2

As per this source;

Save some time, if you want to clean a directory or delete it and you're on windows.

Use This:

    chdir ($file_system_path);
    exec ("del *.* /s /q");

You can use other DEL syntax, or any other shell util. You may have to allow the service to interact with the desktop, as that's my current setting and I'm not changing it to test this.

Else you could find an alternative method here.

Kevin Boyd
  • 12,121
  • 28
  • 86
  • 128
  • it's a bad idea to have to depend on your OS... this only works on Windows and would fail on a Unix system for instance... – patrick Feb 14 '17 at 00:55
1

Try this :

exec('rm -rf '.$user_dir);
Ravinder Singh
  • 3,113
  • 6
  • 30
  • 46
1

This fuction delete the directory and all subdirectories and files:

function DelDir($target) {
    if(is_dir($target)) {
        $files = glob( $target . '*', GLOB_MARK ); //GLOB_MARK adds a slash to directories returned

        foreach( $files as $file )
        {
            DelDir( $file );      
        }

        rmdir( $target );
    } elseif(is_file($target)) {
        unlink( $target );  
    }
}
vinsa
  • 1,132
  • 12
  • 25
0

One safe and good function located in php comments by lprent It prevents accidentally deleting contents of symbolic links directories located in current directory

public static function delTree($dir) { 
   $files = array_diff(scandir($dir), array('.','..')); 
    foreach ($files as $file) { 
      (is_dir("$dir/$file") && !is_link($dir)) ? delTree("$dir/$file") : unlink("$dir/$file"); 
    } 
    return rmdir($dir); 
  } 
AMIB
  • 3,262
  • 3
  • 20
  • 20