PHP: Delete all files from a folder.

In this guide, we are going to show you how to delete all files in a folder using PHP.

Our first example is pretty straight-forward, as we simply loop through the files and then delete them.

Take a look at the following code sample.

//The name of the folder.
$folder = 'temporary_files';

//Get a list of all of the file names in the folder.
$files = glob($folder . '/*');

//Loop through the file list.
foreach($files as $file){
    //Make sure that this is a file and not a directory.
    if(is_file($file)){
        //Use the unlink function to delete the file.
        unlink($file);
    }
}
  1. In this example, we will be deleting all files from a folder called “temporary_files”.
  2. We list the files in this directory by using PHP’s glob function. The glob function basically finds pathnames that match a certain pattern. In this case, we use a wildcard (asterix) to specify that we want to select everything that is inside the “temporary_files” folder.
  3. The glob function returns an array of file names that are in the specified folder.
  4. We then loop through this array.
  5. Using the is_file function, we check to see if it is a file and not a parent directory or a sub-directory.
  6. Finally, we use the unlink function, which deletes the file.

Deleting files in sub-folders.

To delete all files and directories in all sub-directories, we can use recursion.

Here is an example of a recursive PHP function that deletes every file and folder in a specified directory.

function deleteAll($str) {
    //It it's a file.
    if (is_file($str)) {
        //Attempt to delete it.
        return unlink($str);
    }
    //If it's a directory.
    elseif (is_dir($str)) {
        //Get a list of the files in this directory.
        $scan = glob(rtrim($str,'/').'/*');
        //Loop through the list of files.
        foreach($scan as $index=>$path) {
            //Call our recursive function.
            deleteAll($path);
        }
        //Remove the directory itself.
        return @rmdir($str);
    }
}

//call our function
deleteAll('temporary_files');

The function above basically checks to see if the $str variable represents a path to a file. If it does represent a path to a file, it deletes the file using the function unlink.

However, if $str represents a directory, then it gets a list of all files in said directory before deleting each one.

Finally, it removes the sub-directory itself by using PHP’s rmdir function.