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

不羁的心 提交于 2019-12-17 18:06:06

问题


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?


回答1:


Well, there's always

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

where available.




回答2:


rrmdir() -- recursively delete directories:

function rrmdir($dir) { 
  foreach(glob($dir . '/*') as $file) { 
    if(is_dir($file)) rrmdir($file); else unlink($file); 
  } rmdir($dir); 
}



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



回答4:


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.




回答5:


Try this :

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



回答6:


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



回答7:


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


来源:https://stackoverflow.com/questions/1296681/php-simplest-way-to-delete-a-folder-including-its-contents

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