Clue Mediator

Remove all files and subfolders from a folder in PHP

📅April 30, 2020
🗁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

Checkout more articles on 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

<!--?php
// function to delete all files and subfolders from folder
function deleteAll($dir, $remove = false) {
	$structure = glob(rtrim($dir, "/").'/*');
	if (is_array($structure)) {
		foreach($structure as $file) {
			if (is_dir($file))
				deleteAll($file,true);
			else if(is_file($file))
				unlink($file);
		}
	}
	if($remove)
		rmdir($dir);
}<p-->

// folder path that contains files and subfolders
$path = "./uploads";

// call the function
deleteAll($path);

echo "All files and subfolders deleted successfully.";
exit;
?>

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





	<title>
		Remove all files from a folder and their subdirectories in PHP - Clue Mediator
	</title>



	<h2>
		Remove all files - <a href="https://www.cluemediator.com" target="_blank" rel="noopener noreferrer">Clue Mediator</a>
	</h2>
	<div style="line-height: 25px;">
		<a href="./delete-all-files.php" title="Delete all files">Delete all files</a>
	</div>

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