Remove empty subfolders with PHP

后端 未结 6 1365
小鲜肉
小鲜肉 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 23:10

    If you have empty folder within empty folder within empty folder, you'll need to loop through ALL folders three times. All this, because you go breadth first - test folder BEFORE testing its children. Instead, you should go into child folders before testing if parent is empty, this way one pass will be sufficient.

    function RemoveEmptySubFolders($path)
    {
      $empty=true;
      foreach (glob($path.DIRECTORY_SEPARATOR."*") as $file)
      {
         if (is_dir($file))
         {
            if (!RemoveEmptySubFolders($file)) $empty=false;
         }
         else
         {
            $empty=false;
         }
      }
      if ($empty) rmdir($path);
      return $empty;
    }
    

    By the way, glob does not return . and .. entries.

    Shorter version:

    function RemoveEmptySubFolders($path)
    {
      $empty=true;
      foreach (glob($path.DIRECTORY_SEPARATOR."*") as $file)
      {
         $empty &= is_dir($file) && RemoveEmptySubFolders($file);
      }
      return $empty && rmdir($path);
    }
    

提交回复
热议问题