要删除一个目录及其所有子目录、文件,可以使用 rmdir
和 unlink
函数,如下所示:
function deleteDir($dirPath) {
if (!is_dir($dirPath)) {
throw new InvalidArgumentException("$dirPath must be a directory");
}
if (substr($dirPath, strlen($dirPath) - 1, 1) != "/") {
$dirPath .= "/";
}
$files = glob($dirPath . "*", GLOB_MARK);
foreach ($files as $file) {
if (is_dir($file)) {
deleteDir($file);
} else {
unlink($file);
}
}
rmdir($dirPath);
}
以上函数会删除指定的目录及其所有子目录、文件。注意,该函数是递归的,需要谨慎使用,以免不小心删除了重要的文件或目录。