This article has moved to:
http://bsd-noobz.com/blog/how-to-remove-directories-recursively-with-php
At many times we need to empty a directory. Of course PHP has the filesystem functions like unlink() and rmdir() to delete files and directories. At first we may think that simply use rmdir() will solve the problem. Unfortunately it's not. rmdir() only removes empty directory. If the directory is not empty, it will return false.
In order to remove a directory and its contents, we have to remove its contents first, consisting of files and subdirectories. To make things more complicated, the subdirectories also contains files and another subdirectories in it.
It seems like this is a difficult task to solve. But in contrast, this is a very simple recursive function. See the code below.
Listing 1: rmdir_recursive.php
The function determines if argument is a regular file or a directory. If it is a regular file, it will remove the file. If it is a directory, it will remove its contents first by calling the function itself, and then removes the empty directory.
Note that the function above removes a directory. If what you need is remove directory contents, simply delete the line:
rmdir($dir)
in line 20.
South Africa PHP developers on Jan 27, 2010:
MK on Mar 30, 2010:
Daniel on Apr 8, 2010:
Nash on Apr 9, 2010:
Will Smelser on Apr 29, 2010:
| ICQ | 489571630 |
| Skype | dede_bl4ckheart |
| Yahoo | dede_bl4ckheart |
| nashruddin.amin |
Davo on Jul 29, 2009:
Someone with a routine that actually works.
I have experimented with code from people that should be writing novels
Yet this simple little recusancy is just the Duck's guts.
Thank you who ever you are... in my book, you are truly a hero.