Why is even recursion in your function?
public function delete($path) { $it = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::CHILD_FIRST ); foreach ($it as $file) { if (in_array($file->getBasename(), array('.', '..'))) { continue; } elseif ($file->isDir()) { rmdir($file->getPathname()); } elseif ($file->isFile() || $file->isLink()) { unlink($file->getPathname()); } } rmdir($path); }
It works because RII::CHILD_FIRST over the children before the parent. Thus, by the time it reaches the directory, it should be empty.
But the actual error is related to where you delete your directories. In internal directories, you do this in the parent iteration. This means that your root directory will never be deleted. I suggest doing this in a local delete iteration:
public function delete($path) { if(!file_exists($path)) { throw new RecursiveDirectoryException('Directory doesn\'t exist.'); } $directoryIterator = new DirectoryIterator($path); foreach($directoryIterator as $fileInfo) { $filePath = $fileInfo->getPathname(); if(!$fileInfo->isDot()) { if($fileInfo->isFile()) { unlink($filePath); } elseif($fileInfo->isDir()) { if($this->emptyDirectory($filePath)) { rmdir($filePath); } else { $this->delete($filePath); } } } } rmdir($path); }
Notice the two changes. We remove only empty directories within the iteration. Calling $this->delete() on it will handle the deletion for you. The second change is adding the final rmdir at the end of the method ...
source share