<?php
/**
* 递归删除目录及其所有内容
* @param string $path 目录路径
*/
function delDirRecursive(string $path): void {
if (!is_dir($path)) return;
$dh = opendir($path);
while (($file = readdir($dh)) !== false) {
if ($file === '.' || $file === '..') continue;
$full = $path . '/' . $file;
if (is_dir($full)) {
delDirRecursive($full); // 递归删除子目录
} else {
unlink($full); // 删除文件
}
}
closedir($dh);
rmdir($path); // 删除空目录自身
}
// 用法
delDirRecursive('./cache');
?>
readdir() 返回 false 表示结束,需 !== false 判断. .. 避免无限递归rmdir() 删除空目录unlink,目标不受影响<?php
function delDirSPL(string $path): void {
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($files as $file) {
$file->isDir() ? rmdir($file->getPathname()) : unlink($file->getPathname());
}
rmdir($path);
}
?>
CHILD_FIRST 保证先处理子项,再处理父目录。
@ 抑制警告或 try-catch(PHP 7+ Error)is_writable() 避免权限不足报错