PHP Recursively delete empty directories using SPL iterators

I am trying to delete an empty directory tree in PHP using SPL iterators. Consider the following directory structure, in which all directories are empty:

/ TOPDIR

level1 level2 

I tried the following:

 $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator( '/topdir', RecursiveIteratorIterator::CHILD_FIRST )); foreach ($it as $file) { if ($file->isDir()) { rmdir((string)$file); } } 

But RecursiveIteratorIterator::CHILD_FIRST prevents the lower level file from being part of the loop, and I get the standard Directory not empty E_WARNING, because level1 is not empty.

How do I recursively delete an empty directory tree using SPL Iterators? Note. I know how to do this with glob , scandir , etc. Please do not offer these / similar features as solutions.

I feel that I must be missing something very basic here ...

+6
source share
1 answer

This RecursiveIteratorIterator performs the actual visit to child directories. RecursiveDirectoryIterator provides only handles for it.

Therefore, you need to set the CHILD_FIRST flag to RecursiveIteratorIterator , and not to RecursiveDirectoryIterator :

 $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('/topdir', FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST ); foreach ($it as $file) { if ($file->isDir()) { rmdir((string)$file); } } 

To prevent warnings, add the ::SKIP_DOTS flag to RecursiveDirectoryIterator

+9
source

Source: https://habr.com/ru/post/915855/


All Articles