I wonder, what's the easiest way to delete a directory with all its files in it?
I'm using rmdir(PATH . '/' . $value);
to delete a folder, however, if there are files inside of it, I simply can't delete it.
I wonder, what's the easiest way to delete a directory with all its files in it?
I'm using rmdir(PATH . '/' . $value);
to delete a folder, however, if there are files inside of it, I simply can't delete it.
You may use Symfony's Filesystem (code):
However I couldn't delete some complex directory structures with this method, so first you should try it to ensure it's working properly.
I could delete the said directory structure using a Windows specific implementation:
And just for the sake of completeness, here is an old code of mine:
There are at least two options available nowdays.
Before deleting the folder, delete all it's files and folders (and this means recursion!). Here is an example:
And if you are using 5.2+ you can use a RecursiveIterator to do it without needing to do the recursion yourself:
I generally use this to delete all files in a folder:
And then you can do
I want to expand on the answer by @alcuadrado with the comment by @Vijit for handling symlinks. Firstly, use getRealPath(). But then, if you have any symlinks that are folders it will fail as it will try and call rmdir on a link - so you need an extra check.
As seen in most voted comment on PHP manual page about
rmdir()
(see http://php.net/manual/es/function.rmdir.php),glob()
function does not return hidden files.scandir()
is provided as an alternative that solves that issue.Algorithm described there (which worked like a charm in my case) is:
Using DirectoryIterator an equivalent of a previous answer…