Here a small and useful function for removing files by deleting also subdirectories recursive.
this function takes:
$target .. a absolute target path, f.e: /var/www/html/remove_this
$exceptions .. a array of directorynames which don't have to be removed .. usually unused as you want to delete whole directory :-)
$output=true .. outputs a status message of which file or directory the script just has accessed to;
<?php
function delete_files($target, $exceptions, $output=true)
{
$sourcedir = opendir($target);
while(false !== ($filename = readdir($sourcedir)))
{
if(!in_array($filename, $exceptions))
{
if($output)
{ echo "Processing: ".$target."/".$filename."<br>"; }
if(is_dir($target."/".$filename))
{
delete_files($target."/".$filename, $exceptions);
}
else if(is_file($target."/".$filename))
{
unlink($target."/".$filename);
}
}
}
closedir($sourcedir);
if(rmdir($target))
{ return true; }
else
{ return false; }
}
?>
here a example of function call:
<?php
$exceptions = array(".", "..");
if(delete_files("/var/www/html/this_dir", $exceptions, true))
{ echo "deletion successed"; }
else
{ echo "deletion failed"; }
?>
KNOWN ISSUE:
if you call the function with an exception folder and that folder is a childfolder, this function won't be able to remove the parent directory and returns false .. :-/ .. if someone knows a workaround please email me :-)