i have code recursive delete files , directories. works fine has little problem. if $path = /var/www/foo/ delete inside of foo, not foo. want delete foo directory too. idea?
public function delete($path) { if(!file_exists($path)) { throw new recursivedirectoryexception('directory doesn\'t exist.'); } $directoryiterator = new directoryiterator($path); foreach($directoryiterator $fileinfo) { $filepath = $fileinfo->getpathname(); if(!$fileinfo->isdot()) { if($fileinfo->isfile()) { unlink($filepath); } else if($fileinfo->isdir()) { if($this->emptydirectory($filepath)) { rmdir($filepath); } else { $this->delete($filepath); rmdir($filepath); } } } } }
why recurse in function?
public function delete($path) { $it = new recursiveiteratoriterator( new recursivedirectoryiterator($path), recursiveiteratoriterator::child_first ); foreach ($it $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
iterates on children before parent element. time reaches directory, should empty.
but actual error due delete directories. in inner directories in parent iteration. means root directory never deleted. i'd suggest doing in local delete iteration:
public function delete($path) { if(!file_exists($path)) { throw new recursivedirectoryexception('directory doesn\'t exist.'); } $directoryiterator = new directoryiterator($path); foreach($directoryiterator $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); }
note 2 changes. we're deleting empty directories inside of iteration. calling $this->delete()
on handle deletion you. second change addition of final rmdir
@ end of method...
Comments
Post a Comment