This article demonstrates how to delete all files from a directory in PHP.

1. Using glob() function

The standard solution to delete a file from the filesystem is to use the unlink() function. The idea is to get all files in a folder using the glob() function and delete them using unlink() function. The glob() function returns an array containing the pathnames matching the specified pattern, and you can filter out the regular files using the is_file() function.

Download Code

 
The above example deletes all files present in a directory. However, this deletes only the files in the root directory, leaving files in subdirectories untouched. You can extend the solution to recursively delete a directory, as follows: It uses is_dir() to check if the current path is a directory or not.

Download Code

 
It’s worth noting that glob('*') ignores hidden files. If you want to remove the hidden files too, you can use '*' pattern with the GLOB_BRACE flag.

Download Code

2. Using RecursiveDirectoryIterator class

Another option to recursively delete a directory is to use the RecursiveDirectoryIterator class, which provides the interface for iterating recursively over filesystem directories. As an example, the following code deletes all files and subdirectories in the directory, but not the root directory itself.

Download Code

 
It should be noted that the deletion behavior can be easily controlled using the flags. The above example uses FilesystemIterator::SKIP_DOTS and RecursiveIteratorIterator::CHILD_FIRST which skips the dot files and process children before parents in the iteration order.

3. Using DirectoryIterator class

If you don’t need a recursive iterator, you can use the lightweight SplFileInfo iterator DirectoryIterator to list the contents of filesystem directories. It can be used as follows to delete all files from a directory. Since DirectoryIterator is a non-recursive iterator, it doesn’t delete the files present in any of the subdirectories.

Download Code

That’s all there is to deleting all files from a directory in PHP.