PHP Functions for Recursively Deleting Files and Directories
This article provides PHP code examples for recursively removing files and folders, explains the use of unlink() and rmdir() functions, and demonstrates how to delete all ".svn" directories along with their contents.
Sometimes you need to use PHP to delete files and directories; PHP offers built‑in functions for this purpose, and the following code snippets illustrate how to perform recursive deletions.
<?php
function deldir($dir) {
// First delete files in the directory:
$dh = opendir($dir);
while ($file = readdir($dh)) {
if ($file != "." && $file != "..") {
$fullpath = $dir . "/" . $file;
if (!is_dir($fullpath)) {
unlink($fullpath);
} else {
deldir($fullpath);
}
}
}
closedir($dh);
// Delete the current folder:
if (rmdir($dir)) {
return true;
} else {
return false;
}
}
?>The unlink() function deletes a file and returns true on success or false on failure; the rmdir() function removes an empty directory, which must be empty and have appropriate permissions.
Example: delete all ".svn" folders (including their contents) under a given directory.
<?php
function delsvn($dir) {
$dh = opendir($dir);
// Find all ".svn" folders:
while ($file = readdir($dh)) {
if ($file != "." && $file != "..") {
$fullpath = $dir . "/" . $file;
if (is_dir($fullpath)) {
if ($file == ".svn") {
delsvndir($fullpath);
} else {
delsvn($fullpath);
}
}
}
}
closedir($dh);
}
function delsvndir($svndir) {
// First delete files in the directory:
$dh = opendir($svndir);
while ($file = readdir($dh)) {
if ($file != "." && $file != "..") {
$fullpath = $svndir . "/" . $file;
if (is_dir($fullpath)) {
delsvndir($fullpath);
} else {
unlink($fullpath);
}
}
}
closedir($dh);
// Delete the directory itself:
if (rmdir($svndir)) {
return true;
} else {
return false;
}
}
$dir = dirname(__FILE__);
// echo $dir;
delsvn($dir);
?>At the end of the article, several recommended learning resources for PHP, Vue, Laravel, Swoole, and related technologies are listed.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
