note 52358 deleted from function.rmdir by aidan

From: Date: Wed, 15 Apr 2009 04:29:08 +0000
Subject: note 52358 deleted from function.rmdir by aidan
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-153277@lists.php.net to get a copy of this message
Note Submitter: development at lab-9 dot com ---- 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)) { // recurse subdirectory; call of function recursive delete_files($target."/".$filename, $exceptions); } else if(is_file($target."/".$filename)) { // unlink file 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 :-)

« previous php.notes (#153277) next »