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

You may also like...

Leave a Reply

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