Delete All Files of a Certain Type (Using PHP)

In the previous post, I shared a way to process all of the files in a given directory. Specifically, it covers how to read all of the files that have a particular naming convention.

There’s a second part, though:

What if you want to delete all files?

That is, let’s say you’ve processed all of the individual files, and then you want to delete all files that are in the directory from which you were reading them.

Delete All Files

Just as I use glob to read all of the files in a directory, I also use it to delete all files in a directory.

Delete All Files: They are in the trash.

But there’s a caveat to using it this time: We have to use a PHP defined-flag called GLOB_BRACE.

In this instance, not only do we have to pass the parameter for the directory and a pattern to match, but we also have to pass the flag that will take our pattern and match any variant of it.

An Aside on Expressions

For example, say that I define a pattern like {tom}, it will match ‘t,’ ‘o,’ or ‘m.’ And all of this is covered in the manual.

We’re looking to delete all of the files in a directory, so how do we match the files? I typically use the pattern {.,}*. But there’s an important caveat about using commas that you should read.

{includes/.php, core/.php} with a leading space, will only match the former as expected but not the latter

Back To The Code

With that aside done, here’s a look at the function I use to delete the files located in the directory covered in the last post:

The code should be easy to follow. But to make sure I cover each line, here’s what’s happening:

  • I set up two variables to refer to the directory in which the files reside and an array to store a reference to all of the files,
  • I loop through the array, verify that the reference to a file during the current iteration is a file,
  • Then I delete the file.

Depending on your work, there may be additional checks that you want to put in place. It depends on how you’ve set up everything.

But this is a short example to round out the idea of reading all files in a directory and deleting all files in a directory. Generally speaking, perhaps you’ll find these functions useful in the context of a class responsible for managing files.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.