Delete all files from a folder in PHP

Sometimes, we need to delete all files from a folder in PHP. So today we will explain to you how to delete files from a folder using php.

delete images from folder, delete files from directory, unlinks multiple files, loop through delete files from directory, php unlink doesn’t delete file, delete files before specific days,The correct way to delete all files older than 2 days in PHP, Delete files older than x days in php, Delete Files Older than n Number Of days Using PHP, Deleting all files from a folder using PHP, glob() function to get all files from folder, PHP Glob() Function To Match Path, Directory, File Names

Before we start, let’s assume that we have a directory structure like below and we are going to delete all the files from the uploads folder.

Folder Structure - Delete all files from a folder in PHP - Clue Mediator
Folder Structure – Delete all files from a folder – Clue Mediator

Different ways to use the glob() function to delete files

  1. Delete files with .css extension
  2. Delete files that start with ‘spec-’ name
  3. Delete all files
  4. Example

1. Delete files with .css extension

As we discussed, here we will use the glob() function to get a list of the file names from a folder which contains the .css extension.

delete-css-files.php

In the above code, we used the is_file() function to check if a file exists or not. This will help us to filter only files not directories.

Also we used the unlink() function to delete the files from a folder.

That’s it to delete all .css files from a folder.

2. Delete files that start with ‘spec-’ name

Now let’s try to remove specific files from a folder that start with spec- name.

Check the following code to get specific files from a folder by matching a pattern.

We have to follow the same code as written in the first point. Let’s combine all codes together to make it work.

delete-specific-files.php

3. Delete all files

At last, we are going to delete all the files from a folder. So for that we will use glob($path.'/*') function to get all the files from a folder and then delete all the files.

Check the following code to delete all files.

delete-all-files.php

4. Example

Let’s combine all above codes together and create an example where we will delete all files from a folder.

index.php

Run the project and check the below output.

Output - Delete all files from a folder in PHP - Clue Mediator
Output – Delete all files from a folder in PHP – Clue Mediator

That’s it for today.
Thank you for reading. Happy Coding!

Demo & Source Code

Github Repository
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *