note 52358 added to function.rmdir

From: Date: Thu, 28 Apr 2005 16:35:48 +0000
Subject: note 52358 added to function.rmdir
Groups: php.notes 
Request: Send a blank email to php-notes+get-88702@lists.php.net to get a copy of this message
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 :-) ---- Manual Page -- http://www.php.net/manual/en/function.rmdir.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+52358 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+52358&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+52358&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+52358&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+52358&report=yes&reason=useless Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+52358&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+52358&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#88702) next »