Remove empty subfolders with PHP

后端 未结 6 1358
小鲜肉
小鲜肉 2020-12-09 22:38

I am working on a PHP function that will recursively remove all sub-folders that contain no files starting from a given absolute path.

Here is the code developed so

6条回答
  •  遥遥无期
    2020-12-09 22:46

    You can try this.

    function removeEmptySubfolders($path){
    
      if(substr($path,-1)!= DIRECTORY_SEPARATOR){
        $path .= DIRECTORY_SEPARATOR;
      }
      $d2 = array('.','..');
      $dirs = array_diff(glob($path.'*', GLOB_ONLYDIR),$d2);
      foreach($dirs as $d){
        removeEmptySubfolders($d);
      }
    
      if(count(array_diff(glob($path.'*'),$d2))===0){
        $checkEmpSubDir = explode(DIRECTORY_SEPARATOR,$path);
        for($i=count($checkEmpSubDir)-1;$i>0;$i--){
          $path = substr(str_replace($checkEmpSubDir[$i],"",$path),0,-1);
    
          if(($files = @scandir($path)) && count($files) <= 2){
            rmdir($path);
          }
        }
      }
    }
    

提交回复
热议问题