Deleting non empty directory
I assume that you are aware of the rmdir function. This is very useful function, however it has its own limitations. The biggest one is that you are not able to delete non empty folders. We need to build our own function.
First, we will use recursion and second – this actually won’t be a function. We will write a method instead. Of course you may translate it into function, it is very easy (just remove $this->).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public function del_directory( $dir ) { if ( is_dir( $dir ) ) { $objects = scandir( $dir ); foreach( $objects as $object ) { if ( ( $object != '.' ) && ( $object != '..' ) ) { if ( is_dir( $dir . DIRECTORY_SEPARATOR . $object ) ) { $this->del_directory( $dir . DIRECTORY_SEPARATOR . $object ); } else { unlink( $dir . DIRECTORY_SEPARATOR . $object ); } } } rmdir( $dir ); } } |
Please remember – this is a method, part of the class.