How to Delete Directory in PHP (Step by Step)
In this tutorial, we will learn how to delete a directory in PHP. When you are working with file systems in PHP, you will often need to create, read, and delete directories. However, deleting a directory is not always simple as removing a file because a directory may contain subdirectories or multiple files, which makes the process more complex.
Why Delete a Directory in PHP?
We may need to delete a directory in PHP for several reasons:
- To clean up temporary folders after processing.
- To manage uploaded files and directories.
- To maintain file system hygiene and prevent clutter.
- To automatically remove old logs, backups, or cache folders.
Ways to Delete a Directory in PHP
There are mainly two ways to delete a directory in PHP:
- Using the rmdir() function
- Using a custom recursive function
Let’s explore each way one by one with the help of important examples.
PHP rmdir() Function
The rmdir() function in PHP is a built-in function that is used to delete an empty directory. This function returns true on success or false on failure if the directory contains files or subdirectories. Its general syntax is:
rmdir("directory_name");
The rmdir() function accepts one parameter named directory_name that specifies the path of the directory you want to remove.
Example: Delete an Empty Directory
<?php
$dir = "testDir";
// Check if directory exists using is_dir() function.
if (is_dir($dir)) {
// Delete a directory.
if (rmdir($dir)) {
echo "Directory '$dir' deleted successfully.";
} else {
echo "Failed to delete directory '$dir'.";
}
} else {
echo "Directory does not exist.";
}
?>
Output: Directory 'testDir' deleted successfully.
If the directory is empty, it will be removed. If the directory contains files or subdirectories, the rmdir() function will fail and return false.
👉 Important Note:
- The rmdir() function works only for empty directories.
- To delete non-empty directories, you must use a custom recursive function.
Delete a Non-Empty Directory in PHP (Custom Recursive Method)
The rmdir() function works only for empty directories. But in real-life PHP applications, you often need to delete directories that contain files and subdirectories. In such cases, you must use a custom recursive function to remove everything inside the directory before deleting it.
Example: Recursively Delete a Directory
<?php
// Define a function to delete a directory.
function deleteDirectory($dir) {
// Check if the given path is actually a directory.
if (!is_dir($dir)) {
return false; // If it's not a directory, it will stop execution.
}
// Get all files and folders inside the directory.
$items = scandir($dir);
// Apply loop through each item in the directory.
foreach ($items as $item) {
// Skip the special entries "." (current directory) and ".." (parent directory)
if ($item == '.' || $item == '..') {
continue;
}
// Build the full path of the current item.
$path = $dir . DIRECTORY_SEPARATOR . $item;
// If the item is a directory, call this function recursively.
if (is_dir($path)) {
deleteDirectory($path);
}
// If the item is a file, delete it.
else {
unlink($path);
}
}
// After all files and subdirectories are deleted, remove the main directory.
return rmdir($dir);
}
$directory = "uploads";
// Call the function to delete uploads and check if the directory has been deleted.
if (deleteDirectory($directory)) {
echo "Directory '$directory' deleted successfully.";
} else {
echo "Failed to delete directory '$directory'.";
}
?>
Output: Directory 'uploads' deleted successfully.
In this example, we have created a function named deleteDirectory() that accepts a directory path as input and deletes it along with all its files and subdirectories.
Then, we have checked the given path is a directory or not using is_dir() function. If the given path is not directory, it stops execution and returns false.
We have used scandir() function to scan the contents of directory. It retrieves all the items such as files and subfolders inside the directory. Since this function returns an array of files and subdirectories that also includes “.” (current directory) and “..” (parent directory), we have used the continue statement to remove them.
We have used the foreach loop to iterate over each item in the directory and skips “.” and “..” to avoid infinite recursion. The full path of the file or folder is created using the directory separator (/ or \, depending on OS).
If the item is a subdirectory, the function calls itself again (recursion) to delete its contents first. If the item is a file, it is deleted using the unlink() function. Once all files and subdirectories are deleted, the main directory itself is removed using rmdir() function.
Real-Life Use Cases
Here are some common real-life use cases where deleting directories in PHP is useful:
- Deleting uploaded images after processing.
- Clearing cache directories in web applications.
- Removing logs or temporary files periodically.
- Deleting old backup folders using cron jobs.
Conclusion
In PHP, deleting directories depends on whether they are empty or contain files and subdirectories.
- Use rmdir() function for empty directories.
- Use a recursive function for directories with files and subdirectories.
- Always validate paths before deletion to prevent security vulnerabilities.
By following these methods, you can safely manage file system directories in your PHP projects.