note 75205 deleted from function.rmdir by aidan

From: Date: Wed, 15 Apr 2009 04:24:49 +0000
Subject: note 75205 deleted from function.rmdir by aidan
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-153256@lists.php.net to get a copy of this message
Note Submitter: jeremiah (at) jkjonesco (dot) com ---- Here is a very clean, readable (hopefully) recursive way to delete everything in a directory. This also handles deleteing links to ensure a non-recursive follow through a symlink and just deletes the link instead. It is in the form of a class so that you can plug it right into your existing classes or libraries. Here is how to use the recursive delete (unlink) function: <?php $path = '/absolute/path/to/some/file/filename.ext'; if(!FileFunctions::unlink($path)) echo "One or more files could not be deleted"; ?> Here is the class: <?php /** * Provides file functionality that extends the built-in PHP functions * * @author jjones * */ class FileFunctions { /** * Recursive unlink function * * This will delete the provided path. If the path is a * directory, it will delete the directory. It will * recursively delete any subdirectories/files. * * @param String $path Path to file/directory to recursively unlink */ public function unlink($path) { /* make sure the path exists */ if(!file_exists($path)) return false; /* If it is a file or link, just delete it */ if(is_file($path) || is_link($path)) return @unlink($path); /* Scan the dir and recursively unlink */ $files = scandir($path); foreach($files as $filename) { if($filename == '.' || $filename == '..') continue; $file = str_replace('//','/',$path.'/'.$filename); self::unlink($file); }//end foreach /* Remove the parent dir */ if(!@rmdir($path)) return false; return true; }//end function unlink }//end class FileFunctions ?>

« previous php.notes (#153256) next »