Retainer software Development
In today’s fast-paced digital age, businesses require robust solutions to manage long-term client relationships and recurring engagements efficiently. Retainer software provides an excellent too
Read MoreSign Up Now and Get FREE CTO-level Consultation.
Deleting files and folders is a common requirement in PHP development. Whether you're building a file manager, document management system, backup application, CMS, or upload feature, there will be times when you need to remove every file and subfolder inside a directory.
While deleting a single file is straightforward using PHP, deleting an entire folder along with all its nested files and directories requires a recursive approach.
In this guide, you'll learn how to delete all files and subfolders from a folder in PHP safely and efficiently. We'll cover multiple methods, explain each function in detail, discuss security best practices, and provide complete working examples.
Many PHP applications automatically generate temporary files, uploaded documents, cache files, reports, logs, or backups. Over time, these files consume valuable server storage.
Here are some common situations where deleting folders is useful:
Clearing cache folders
Removing temporary upload files
Resetting application storage
Deleting user-generated content
Cleaning backup directories
Removing expired documents
Deleting image thumbnails
Clearing log files
Resetting test environments
Cleaning export folders
Automating these tasks helps maintain application performance and prevents unnecessary storage usage.
Suppose your directory looks like this:
uploads/
??? images/
? ??? image1.jpg
? ??? image2.jpg
?
??? documents/
? ??? invoice.pdf
? ??? report.docx
?
??? temp/
? ??? cache.txt
?
??? sample.txt
If you want to delete everything inside uploads, your PHP script should remove:
All files
All folders
All nested folders
Everything inside nested folders
Finally, the uploads folder itself can either remain empty or also be deleted depending on your requirement.
Before writing the code, let's understand the important PHP functions.
Returns all files and folders inside a directory.
Example:
$files = scandir("uploads");
Output:
.
..
documents
images
temp
sample.txt
Checks whether the given path is a directory.
Example:
is_dir("uploads/images");
Returns:
true
Deletes a file.
Example:
unlink("uploads/sample.txt");
Deletes an empty directory.
Example:
rmdir("uploads/temp");
Note:
It only removes empty folders.
Checks whether a file or directory exists.
Example:
file_exists("uploads");
If your folder contains only files and no subfolders, you can use this simple approach.
$folder = "uploads/";
$files = glob($folder . '*');
foreach($files as $file)
{
if(is_file($file))
{
unlink($file);
}
}
echo "Files deleted successfully.";
?>
Gets all files using glob()
Checks whether each item is a file
Deletes each file using unlink()
This method is suitable only when there are no subdirectories.
Most real-world projects contain nested directories.
The following recursive function removes everything inside a folder.
function deleteFolder($folder)
{
if (!file_exists($folder))
{
return;
}
$items = scandir($folder);
foreach ($items as $item)
{
if ($item == "." || $item == "..")
{
continue;
}
$path = $folder . DIRECTORY_SEPARATOR . $item;
if (is_dir($path))
{
deleteFolder($path);
rmdir($path);
}
else
{
unlink($path);
}
}
}
deleteFolder("uploads");
echo "Folder cleaned successfully.";
?>
Check whether the folder exists.
file_exists($folder)
Read all files.
scandir($folder)
Ignore
.
..
These are system entries.
Check whether each item is a folder.
is_dir($path)
If it's a folder:
Call the function again
Delete its contents
Remove the empty folder
If it's a file:
Delete using
unlink($path);
Sometimes you want to remove the main folder as well.
Example:
function removeDirectory($directory)
{
if (!file_exists($directory))
{
return;
}
foreach(scandir($directory) as $item)
{
if($item == "." || $item == "..")
{
continue;
}
$path = $directory . DIRECTORY_SEPARATOR . $item;
if(is_dir($path))
{
removeDirectory($path);
}
else
{
unlink($path);
}
}
rmdir($directory);
}
removeDirectory("uploads");
echo "Directory deleted.";
?>
After execution:
uploads/
will also disappear.
PHP also provides an object-oriented solution.
$directory = "uploads";
$iterator = new RecursiveDirectoryIterator(
$directory,
RecursiveDirectoryIterator::SKIP_DOTS
);
$files = new RecursiveIteratorIterator(
$iterator,
RecursiveIteratorIterator::CHILD_FIRST
);
foreach($files as $file)
{
if($file->isDir())
{
rmdir($file->getRealPath());
}
else
{
unlink($file->getRealPath());
}
}
rmdir($directory);
echo "Deleted Successfully.";
?>
This method is suitable for enterprise-level applications.
Deleting files is irreversible. Follow these precautions before running any deletion script.
Wrong path:
/
Correct path:
uploads/
Before deleting important folders:
Export files
Download backups
Store archives
Only administrators should access deletion scripts.
Never expose delete functions publicly.
Do not allow users to pass arbitrary folder names.
Instead of:
$_GET['folder']
Use:
$allowedFolders = [
"uploads",
"cache",
"temp"
];
Avoid:
../../../
Always sanitize paths.
Error:
Permission denied
Solution:
Ensure the PHP process has write permission.
Error:
Directory not empty
Reason:
You attempted
rmdir()
before deleting files.
Error:
No such file or directory
Solution:
Check
file_exists()
before deleting.
When deleting thousands of files:
Use recursive deletion
Process files in batches if needed
Increase execution time
Example:
set_time_limit(300);
Increase memory if required:
ini_set('memory_limit', '512M');
For safe and efficient file deletion in PHP, follow these recommendations:
Always check whether the folder exists.
Use recursive functions for nested directories.
Skip the . and .. entries.
Validate folder paths before deleting.
Log deleted files for auditing.
Restrict deletion access to authorized users.
Create backups before running cleanup scripts.
Test scripts in a development environment before deploying to production.
Following these practices helps avoid accidental data loss and improves the reliability of your application.
PHP developers frequently use recursive folder deletion in many applications.
Remove unused media files and temporary uploads.
Delete expired product images and cached files.
Clear assignment submissions after a course ends.
Remove user files after account deletion.
Delete generated reports and export files.
Automatically remove outdated backup archives.
Delete resized thumbnails and temporary images.
Reset directories before running automated tests.
You can use the glob() function to retrieve all files in a folder and delete each file using unlink(). This method works well when the folder contains only files and no subdirectories.
Create a recursive function that scans every file and subfolder, deletes files with unlink(), removes empty directories using rmdir(), and continues until the entire folder structure is cleaned.
unlink() deletes individual files, while rmdir() removes empty directories. Since rmdir() cannot delete folders containing files, you must first remove all files and subfolders before deleting the directory.
Yes. PHP can delete a non-empty folder by recursively removing all nested files and subdirectories before calling rmdir() on the now-empty parent folder.
It is safe when implemented carefully. Always validate the target directory, avoid user-controlled paths, restrict access to administrators, and maintain backups before performing deletion operations.
rmdir() only works on empty directories. If the folder still contains files or subfolders, the function will fail until those contents are deleted first.
Use fixed directory paths, validate input, verify the folder exists, restrict permissions, test in a development environment, and back up important data before running deletion scripts.
For most projects, a recursive function is simple and easy to understand. For larger or enterprise applications, RecursiveDirectoryIterator offers a cleaner, object-oriented approach and handles complex directory structures effectively.
Deleting all files and subfolders from a folder in PHP is a common task for developers working with uploads, cache management, backups, and file storage systems. While deleting individual files is simple, handling nested directories requires a recursive approach to ensure every file and folder is removed correctly.
By using functions such as scandir(), unlink(), rmdir(), and is_dir(), you can build a reliable cleanup script that works across different project types. Always prioritize security by validating paths, restricting access, checking permissions, and creating backups before deleting important data.
Whether you're developing a small website or a large-scale PHP application, implementing safe and efficient folder deletion techniques will help keep your server organized, improve storage management, and maintain optimal application performance.
Recursive folder deletion is the process of removing all files and nested subfolders inside a directory automatically. It is commonly used for clearing cache, temporary files, uploads, backups, and old application data.
PHP developers, web application developers, CMS developers, eCommerce website owners, and system administrators can use recursive file deletion to automate file management and keep server storage organized.
Developers delete files and folders to free up storage space, remove temporary files, clear cache directories, delete expired uploads, reset testing environments, and maintain better application performance.
The rmdir() function only removes empty directories. If the folder contains files or subfolders, you must first delete those contents before calling rmdir().
You can create a recursive function that scans the directory, deletes every file using unlink(), removes nested folders using rmdir(), and continues until the entire folder is cleaned.
Use the glob() function or scandir() to retrieve all files inside the directory and delete each file with unlink(). This keeps the parent folder intact while removing its contents.
Temporary files should be deleted after file processing, report generation, image conversion, uploads, cache creation, or scheduled maintenance to avoid unnecessary storage consumption.
Recursive deletion is recommended when folders contain multiple levels of subdirectories or a large number of files, making manual deletion inefficient and time-consuming.
Checking with file_exists() prevents PHP warnings or errors and ensures your script only attempts to delete valid directories.
Always validate the folder path, create backups, restrict deletion access to administrators, check file permissions, and test your script in a development environment before using it on a live server.
Request a FREE Business Plan.
+91 ▼
In today’s fast-paced digital age, businesses require robust solutions to manage long-term client relationships and recurring engagements efficiently. Retainer software provides an excellent too
Read More
In today’s digital era, businesses worldwide are racing to innovate faster, operate leaner, and scale smarter. One strategy stands out as a game?changer: partnering with an Offshore Software Dev
Read More
In this blog post, I’ll show you ways to line up Gmail together with your custom email for free of charge. While Gmail a part of this method is 100% free,
Read More