Recursively Deleting a Directory and Files

I&squo;ve recently had to write a PHP script that needed to delete a directory and all sub directories and files within the directory. With PHP, there are functions available to delete a directory and delete a file.

Remove a directory using rmdir( )

The “rmdir” PHP function removes a directory. The only catch is that the directory needs to be empty. This function alone it&squo;s useless for my needs.

Deleting a file using unlink( )

The “unlink” PHP function deletes a file. Again, this function only deletes files not directories. So on its own is useless for what I needed.

My Solution for Recursive Deletion of a Directory

The key to my solution is to utilize the RecursiveIteratorIterator class and the RecursiveDirectoryIterator class. Basically, the idea is to iterate through all the “inner” elements of a passed directory – start at the end of the directory hierarchy and work your way back to the root.

The following function takes the path to the directory you want to delete. It then creates an instance of the Recursive Iterators and proceeds to loop through all the elements starting from the end of the hierarchy. For each element found while iterating through, we determine if its a file or directory and execute one of the two functions (unlink() or rmdir()) as described above.

function clearDirectory( $directory ){	$path = $directory ;
	if( !is_dir( $path ) ) return ;

	$dir = new RecursiveIteratorIterator( 
             new RecursiveDirectoryIterator($path),
             RecursiveIteratorIterator::CHILD_FIRST
        ) ;

	for ($dir->rewind(); $dir->valid(); $dir->next()) {
            if ($dir->isDir()) {
                rmdir($dir->getPathname());
            } else {
                unlink($dir->getPathname());
            }
        }
        rmdir($path);
}
ttessier

About ttessier

Professional Developer and Operator of SwhistleSoft
This entry was posted in Web Development. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *