Recursively Deleting a Directory

Problem

You want to delete the contents of a directory.

You want to delete everything recursively, all files and subdirectories.

Solution

Use the File::deleteDirectory() method.

$success = File::deleteDirectory($directory);

The method will return false if the directory doesn't exist. Otherwise it returns true when complete.

If you want to preserve the top level directory, pass a second argument.

$success = File::deleteDirectory($directory, true);

This will keep $directory itself from being removed.

Discussion

This method can quietly fail.

If there's an issue deleting one of the files, this method has the potential of failing quietly. It can return true even if one or more files are not actually deleted.

If you're not preserving the top level directory, you can always perform a quick File::exists() check on the directory to verify everything's been deleted.

comments powered by Disqus