How to delete entire folders/sub-folders (with all files contained within) in PHP « Kevin Pajak – Interactive Web Developer/Designer – BLOG

How to delete entire folders/sub-folders (with all files contained within) in PHP

March 31st, 2010

Thanks to PeejAvery @CodeGuru.com for turning me on to this one (with the original code here).

Here’s the code:

function rrd($directory, $empty=FALSE){
if(substr($directory,-1) == ‘/’){$directory = substr($directory,0,-1);}
if(!file_exists($directory) || !is_dir($directory)){return FALSE;}
elseif(!is_readable($directory)){return FALSE;}
else{
$handle = opendir($directory);
while (FALSE !== ($item = readdir($handle))){
if($item != ‘.’ && $item != ‘..’){
$path = $directory.’/’.$item;
if(is_dir($path)){rrd($path);}
else{unlink($path);}
}
}
closedir($handle);
if($empty == FALSE){if(!rmdir($directory)){return FALSE;}}
return TRUE;
}
}

(Just make sure you add a direct call to the PHP function, or you’ll get an error. Here’s how I did that:

Put rrd($username, $empty=FALSE); just beneath the function ;) .

Happy coding everybody.

Tags:

Leave a Reply