Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
PHP: Unlink All Files Within A Directory, and then Deleting That Directory
In PHP, removing a directory and all its contents requires unlinking all files first, then removing subdirectories recursively. PHP provides several approaches using functions like glob(), unlink(), and rmdir().
Note: File system operations require proper permissions. Ensure the PHP script has write access to the target directory.
Method 1: Recursive Directory Removal
This function recursively removes all files and subdirectories within a directory ?
<?php
function recursive_directory_removal($directory) {
foreach(glob("{$directory}/*") as $file) {
if(is_dir($file)) {
recursive_directory_removal($file);
} else {
unlink($file);
}
}
rmdir($directory);
}
// Usage
recursive_directory_removal('/path/to/directory');
echo "Directory removed successfully.";
?>
Method 2: Using array_walk() (PHP 5.3+)
A more concise approach using anonymous functions for file removal ?
<?php
$dir = '/path/to/directory';
// Remove all files in directory
array_walk(glob($dir . '/*'), function ($file) {
if (is_file($file)) {
unlink($file);
}
});
// Remove the directory itself
rmdir($dir);
echo "Directory cleaned and removed.";
?>
Method 3: Using RecursiveDirectoryIterator
PHP's SPL provides a more robust solution for complex directory structures ?
<?php
function removeDirectory($path) {
$iterator = new RecursiveDirectoryIterator($path, 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($path);
}
// Usage
removeDirectory('/path/to/directory');
echo "Directory structure removed completely.";
?>
Comparison
| Method | PHP Version | Handles Nested Dirs | Performance |
|---|---|---|---|
| Recursive Function | All versions | Yes | Good |
| array_walk() | 5.3+ | No | Fast |
| RecursiveDirectoryIterator | 5.1+ | Yes | Best |
Conclusion
Use RecursiveDirectoryIterator for complex directory structures, the recursive function for simple cases, and array_walk() for single-level directories. Always ensure proper error handling and permissions before deletion.
Advertisements
