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

后端 未结 7 2017
刺人心
刺人心 2020-12-08 14:00

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:



        
相关标签:
7条回答
  • 2020-12-08 14:20

    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 );  
        }
    }
    
    0 讨论(0)
  • 2020-12-08 14:23

    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); 
      } 
    
    0 讨论(0)
  • 2020-12-08 14:33

    rrmdir() -- recursively delete directories:

    function rrmdir($dir) { 
      foreach(glob($dir . '/*') as $file) { 
        if(is_dir($file)) rrmdir($file); else unlink($file); 
      } rmdir($dir); 
    }
    
    0 讨论(0)
  • 2020-12-08 14:33

    Try this :

    exec('rm -rf '.$user_dir);
    
    0 讨论(0)
  • 2020-12-08 14:34
    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);
      }
     }
    
    0 讨论(0)
  • 2020-12-08 14:34

    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.

    0 讨论(0)
提交回复
热议问题