How to Delete Directory in PHP

Subodh Poudel Feb 02, 2024
  1. Use the rmdir() Function to Delete an Empty Directory in PHP
  2. Use Recursion to Delete Non-Empty Directory in PHP
How to Delete Directory in PHP

This tutorial will explain two ways of deleting a directory in PHP. Here, we will deal with two scenarios.

The first one deletes an empty directory, and the second one deletes a non-empty directory.

Use the rmdir() Function to Delete an Empty Directory in PHP

We can use the rmdir() function to delete an empty directory in PHP. The function is an in-built PHP function.

The function deletes the directory only if there are no contents inside it. We can supply the directory to be deleted as the parameter to the rmdir() function.

The function returns true in case of success and false otherwise.

The directory should exist to remove a directory. We will use the mkdir() function to create a directory for the demonstration.

The function takes the pathname as the parameter.

For example, create a variable $path and store the pathname of a directory to be created. Next, use the mkdir() function with the $path as the parameter.

Example Code:

$path =$_SERVER['DOCUMENT_ROOT']."/newFolder";
mkdir($path);

The above code example creates a directory newFolder in the PHP document root. When you print the $path variable, the output looks like this in Linux.

/var/www/html/newFolder

In Windows, the output is somewhat like this.

C:\xampp\htdocs\newFolder

Since we have created a directory, now it’s time to delete it using rmdir().

Example Code:

if(is_dir($path)){
 rmdir($path);
 echo "the directory is deleted";
}

Output:

the directory is deleted

We checked if the directory exists using the is_dir() function and the rmdir() function to delete the myFolder directory in the document root.

Use Recursion to Delete Non-Empty Directory in PHP

As we know that rmdir() only deletes the empty directory, we need to use a recursive functionality and rmdir() to delete a non-empty directory in PHP. In this method, we will use a couple of PHP functions like array_diff(), scandir() and unlink().

The array_diff() function takes multiple arrays as parameters and returns an array with the values that only exist on the first parameter array.

The scandir() function lists all the files and directories of a specified path. The unlink() function deletes the file specified in its parameter.

The concept behind deleting a directory deals recursively with first finding all the files and folders inside a directory. Then, a loop is created to traverse all the contents inside the parent directory.

The recursive operation is applied for each folder inside the parent directory until the depth is reached. At the depth, the file is deleted using the unlink() function.

The program recurses back to its traversed path and deletes all the files. After deleting all the files, finally, the parent directory is deleted.

Let’s consider a scenario where the directory structure looks like this.

testFolder
├── abc.png
├── abc.text
└── sub
 └── abc.jpeg

The code example below deletes testFolder recursively.

Example Code:

function deleteDirectory($path){

 $files = array_diff(scandir($path), array('.','..'));
 foreach($files as $file){
 (is_dir("$path/$file")) ? deleteDirectory("$path/$file") : unlink("$path/$file");
 }
 return rmdir($path);
}
$path =$_SERVER['DOCUMENT_ROOT']."/testFolder";
deleteDirectory($path);

Here, the function deleteDirectory() is a user-defined function that takes a parameter $path, which is the pathname of the directory to be deleted. testFolder is the $path supplied.

Firstly, the nested scandir() function executes. It lists all the contents of the testFolder directory as an array.

Array ( [0] => . [1] => .. [2] => abc.png [3] => abc.text [4] => sub )

Next, we have used the array_diff() function to remove . and .. from the above array. The single dot represents the current directory, while the double dot represents the parent directory.

As a result, the $files array contains abc.png, abc.text and sub. Then, we used the foreach() loop to iterate through these files and folders.

Inside the loop, we checked if the iterable is a directory. But, the first two items are not.

So, they are removed using the unlink() function. The third iterable sub is a directory, meeting the condition.

So, the function deleteDirectory() is recursively called. This time, the directory only has a single file inside of it.

The file gets deleted with the unlink() function as the other files. Finally, the execution exits the loop.

Next, the sub directory gets deleted with the rmdir() function. Then, the recursive tree traverses back, and the parent directory testFolder gets deleted.

Thus, we learned how to delete a directory recursively using various functions in PHP.

Subodh Poudel avatar Subodh Poudel avatar

Subodh is a proactive software engineer, specialized in fintech industry and a writer who loves to express his software development learnings and set of skills through blogs and articles.

LinkedIn

Related Article - PHP Directory