I have here a piece of PHP code that deletes a directory and all files in it if present. However, I'm not too sure about it, it looks to me like it'll delete all sub-maps too and then files in those and so on...
I basically want to give and optional true/false parameter to select wheter or not to delete sub directories. Or would it be better practice to make 2 functions? The first to completely empty the folder and the seconds the delete both the folder and everything in it.
Here's the code:
function delete_directory($dirname) {
if (is_dir($dirname)) {
$dir_handle = opendir($dirname);
if (!$dir_handle) return false;
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file)){
@unlink($dirname."/".$file);
}else {
delete_directory($dirname.'/'.$file);
}
}
}
closedir($dir_handle);
}
@rmdir($dirname) or die("Could not remove directory.");
return true;
}
And what I'm basically wondering is: what can go wrong here? Is there a situation where this piece of code can seriously screw up? I've been debugging it with Netbeans for a few hours now, and tried a lot of different scenarios. Now I'm kinda stuck and wondering if the guys at StackoverFlow can find a flaw in the code?