recursive folder delete is very slow - please help

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jasongr
Forum Contributor
Posts: 206
Joined: Tue Jul 27, 2004 6:19 am

recursive folder delete is very slow - please help

Post by jasongr »

Hello

I have written my own function that knows how to delete the content of a non-empty folder. They function recursively deletes the content of all the files and subfolders of the function.

The problem is that when I run this function on a folder which contains numerous subfolders anf files, it runs for ~40 seconds before finishing successfully.
When I let Windows Explorer do the same thing, it completes the job in less than 2 seconds.
What could be so inefficient in my code? or maybe its the way PHP is parsed?

Here is my function:

Code: Select all

function deleteFolder($folder, $enableRecursiveDelete = true) {
  if ($dirHandle = opendir($folder)) {
      while (($file = readdir($dirHandle)) !== false) {
        $currentEntry = $folder . $file;
        if (is_file($currentEntry)) {
          if (!unlink($currentEntry)) {
      	// cannot delete a file
          }
        }
        else if (is_dir($currentEntry) && $enableRecursiveDelete) {
          if ($file == '.' || $file == '..') {
            continue;
          }
          deleteFolder($currentEntry . "/", true);      		
        }
      }
      closedir($dirHandle);
   }
   else {
     // cannot obtain a refernce to the folder
   }
   		
   if (!rmdir($folder)) {
      // cannot delete the now empty folder
   }
}
Help would be appreciated
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

In a unix environment a system call to rm -rf does the trick ;)

If i remember well, windows has something like DELTREE /y ? meaby that such a system call is faster than using php's filehandling routines...
Post Reply