PHP: Simplest way to delete a folder (including its contents)

醉酒当歌 提交于 2019-11-28 06:16:20

Well, there's always

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

where available.

Yuriy

rrmdir() -- recursively delete directories:

function rrmdir($dir) { 
  foreach(glob($dir . '/*') as $file) { 
    if(is_dir($file)) rrmdir($file); else unlink($file); 
  } rmdir($dir); 
}
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);
  }
 }

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.

Try this :

exec('rm -rf '.$user_dir);

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

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); 
  } 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!