php - Delete directory with files in it? -
I wonder, what's the easiest way to delete a directory with all its files in it?
i
At least two options are available now.
-
Before deleting the folder, delete all its files and folders (and this means that recycling!). Here is an example:
publicDefault function deleteDir ($ dirPath) {if (! Is_dir ($ dirPath)) {new invalid argument exception ("$ dirPath must be a directory"); } If (substrate ($ dirPath, strlen ($ dirPath) - 1, 1)! = '/') {$ DirPath = '/'; } $ Files = glob ($ dirPath; '*', GLOB_MARK); Foreign Currency (Dollar Files $ $) {if_dir ($ file)} {self :: deleteDir ($ file); } Else {unlink ($ file); }} Rmdir ($ dirPath); }
And if you are using 5.2+ then you can use a recursive iterator to do it without having to repeat yourself. :
$ dir = 'samples' DIRECTORY_SEPARATOR 'Sampledirtree'; $ It = new recurring directoryitter ($ dir, recursive directory iterator :: SKIPDOTS); $ Files = new recursiveitter iterator ($ this, recursiveitter iterator :: CHILD_FIRST); Foreign Currency ($ files as $ $) {if ($ file-> isDir ()) {rmdir ($ file-> getRealPath ()); } Else {unlink ($ file-> getRealPath ()); }} Rmdir ($ dir);
Comments
Post a Comment