Remove all files and subfolders from a folder in PHP

Today we’ll let you know how to remove all files and subfolders from a folder in PHP. We have already written an article to delete all files from a folder in PHP.

As per the request of our readers, we decided to provide the solution to their query for recursively delete a directory and its entire contents using PHP.

Delete All Files and Sub Folders from a Folder in PHP, Remove all files, folders and their subfolders with php, How to recursively delete a directory and its entire contents, Recursively Remove a Directory in PHP, php code to delete folder with files, php delete files matching pattern, php list files in directory and subdirectories, how to delete images from folder in php

Steps to remove all files from a folder and their subdirectories

  1. Function to delete all files
  2. Execute function
  3. Output

1. Function to delete all files

Here we write a function to delete all files and subfolders from the folder.

delete-all-files.php

In the above function, we passed the two parameters where the first parameter indicates the path of the main folder and second one is an optional parameter that we set default false. If it is false then remove the folder and files otherwise only files will be removed.

Here we used the rmdir function to delete the folder that we can not execute before making it empty.

2. Execute function

Let’s create a simple page that helps us to execute the above function on click of a tag.

index.php

3. Output

Run the code and check the output.

Output - Remove all files and subfolders from a folder in PHP - Clue Mediator
Output – Remove all files and subfolders 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...

5 Responses

  1. Amir J. says:

    Thank you, very useful.

  2. Amir J. says:

    Is it possible to make it delete contents that are older than X time! let say older than 24 hours?
    Thank you

  3. Amir J. says:

    sorry something went wrong when in the copy and paste!! please delete that, if you interested i can email it to you.
    kind regards

Leave a Reply

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