PHP’s rmdir function does not allow the deletion of a folder if it is not empty. The rmdirr function below allows the removal of a folder and all its contents recursively, as would rm -rf on linux.
All good code should include tests, so here we go:
This simple testing script should yield a “TEST PASSED” message when run from your browser or command line.
Although I worry that the paradigm-of-choice may overwhelm some readers, in the interests of completeness I have also included a stack based (instead of recursion based) version of rmdirr below:
Rather than the function calling itself once for each directory, this function maintains an internal stack. Because this function uses the error suppression operator it incurs a speed penalty; however, it will work for very deep directory structures.
The recursive method can cause PHP to segfault when PHP’s own internal stack grows too large (stack overflow), but this is only a problem if you have directories nested 1000+ layers deep.
Summary: use the recursive method (listed first) unless you really don’t like recursion, or have a very deep tree structure. Happy deleting!