PHP for all it’s wonderful things can’t delete a non-empty folder. Every time I have to delete a folder I looked it up in google and used the first code that would sort of work. Well today I needed to delete folders but I needed something robust that handled errors better than what I was able to find. So here is my recursive directory delete function:
function RemoveDir($path){ if($path == ""){ return true; } if(!file_exists($path)){ return true; } if(is_dir($path)){ $handle = opendir($path); while(false !== ($entry = readdir($handle))){ if ($entry != '.' && $entry != '..') { $result = RemoveDir($path.'\\'.$entry); if($result == false){ return false;} } } closedir($handle); if(!rmdir($path)) { return false; } }else{ chmod($path,0777); if(!unlink($path)) return false; } } return true; }
First I check to see if we have something valid to delete. If we are trying to delete something non existent then we have succeeded. This is handled by:
if($path == ""){ return true; } if(!file_exists($path)){ return true; }
We also need a to define the final statement in our case the lowest possible solution is deleting a single file:
chmod($path,0777); if(!unlink($path)) return false; }
in case we fail we return false, We use the false to stop the recursive call. Now the magic happens on this next statement:
if(is_dir($path)){ $handle = opendir($path); while(false !== ($entry = readdir($handle))){ if ($entry != '.' && $entry != '..') { $result = RemoveDir($path.'\\'.$entry); if($result == false){ return false;} } } closedir($handle); if(!rmdir($path)) { return false; } }
We start by opening the directory and parsing all of its entries then we pass the entries back to our function. In case we obtain a false result we stop by returning false. If no error are found then we simply delete the given path.
I hope someone finds this helpful
Leave a Reply