How to delete all files from a folder using PHP?

Spread the love

Sometimes, we want to delete all files from a folder using PHP.

In this article, we’ll look at how to delete all files from a folder using PHP.

How to delete all files from a folder using PHP?

To delete all files from a folder using PHP, we can call glob to get an array of file path strings.

And then we call unlink to remove the files in a loop.

For instance, we write

$files = glob('path/to/temp/*');

foreach ($files as $file) { 
    if (is_file($file)) {
        unlink($file);        
    }
}

to get the file paths in the path/to/temp folder with glob.

Then we use a foreach loop to loop through the $files array.

In it, we call is_file to check if the file at $file is a file.

If it is, we call unlink to delete the file at $file.

Conclusion

To delete all files from a folder using PHP, we can call glob to get an array of file path strings.

And then we call unlink to remove the files in a loop.

Leave a Reply

Your email address will not be published.