PHP函数删除目录及其所有子内容。 [关闭]

   function rrmdir($dir) { 
        if (is_dir($dir)) { 
         $objects = scandir($dir); 
         foreach ($objects as $object) { 
           if ($object != "." && $object != "..") { 
             if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object); 
           } 
         } 
         reset($objects); 
         rmdir($dir); 
        } 
    }

I have this function to delete a directory and all its contents (sub directories and sub files).

This function works great and can delete over 5k files in just a second or two.

But does anyone have any suggestions on optimizing this function?

Also ... if anyone has any "system" or method to securely host custom php functions on one server and call them on other servers let me know... that would be awesome as I have a huge collection of functions and I work off of 3 servers and would love to have them all in one location. I use cPanel's global prepend to include all my functions in all my php files easily and that works extremely well BUT if there was a way to simply call a remotely hosted PHP file into the prepend file that is included in each file on the server that would be superb... Any suggestions for a similar setup would be awesome.

while loop should be faster then foreach, also order of if statement does matter.

function removeDirectory($path)
{
    $path = rtrim($path, '/').'/';
    $files = scandir($path);
    $i = count($files);

    while (--$i) {
        $file = $files[$i];
        $fullpath = $path.$file;

        is_file($fullpath) 
        ? @unlink($fullpath)
        : ($file != '.' and $file != '..' and removeDirectory($fullpath));
    }

    rmdir($path);

    return true;
}

if you are allowed to to do shell execution you can execute the simple linux function

$out = shell_exec('rm -rf /path/to/directory');

and you can do

var_dump($out);

to check out the result if it was removed or not.