遞迴刪除目錄需處理檔案、子目錄、權限、符號連結、錯誤處理等細節。本文提供生產環境可用的完整實作。
<?php
function deleteDirectory(string $dir): bool {
if (!is_dir($dir)) {
return false;
}
$dh = opendir($dir);
if (!$dh) {
return false;
}
while (($file = readdir($dh)) !== false) {
if ($file === '.' || $file === '..') continue;
$path = $dir . '/' . $file;
if (is_dir($path)) {
deleteDirectory($path); // 遞迴刪除子目錄
} else {
unlink($path); // 刪除檔案
}
}
closedir($dh);
return rmdir($dir); // 刪除空目錄
}
$dir = "./fakeDir";
deleteDirectory($dir);
?>
<?php
/**
* 安全遞迴刪除目錄
*
* @param string $dir 目錄路徑
* @param array $options 選項
* @return bool 成功與否
* @throws RuntimeException 關鍵錯誤
*/
function deleteDirectoryRecursive(string $dir, array $options = []): bool {
$defaults = [
'followSymlinks' => false, // 是否跟隨符號連結刪除目標
'continueOnError' => false, // 遇錯繼續或拋出例外
'maxDepth' => 1000, // 最大遞迴深度防無限迴圈
'chmodFiles' => 0644, // 刪除前嘗試修改檔案權限
'chmodDirs' => 0755, // 刪除前嘗試修改目錄權限
];
$opts = array_merge($defaults, $options);
// 正規化路徑
$dir = rtrim($dir, '/\\');
if (!file_exists($dir)) {
return true; // 不存在視為成功(冪等性)
}
if (!is_dir($dir)) {
throw new InvalidArgumentException("路徑非目錄: $dir");
}
// 檢查符號連結
if (is_link($dir) && !$opts['followSymlinks']) {
return unlink($dir); // 只刪除連結本身
}
// 遞迴深度保護
static $depth = 0;
if (++$depth > $opts['maxDepth']) {
throw new RuntimeException("遞迴深度超過限制: $dir");
}
$dh = @opendir($dir);
if (!$dh) {
$error = error_get_last();
throw new RuntimeException("無法開啟目錄 $dir: " . ($error['message'] ?? '未知錯誤'));
}
$errors = [];
while (($file = readdir($dh)) !== false) {
if ($file === '.' || $file === '..') continue;
$path = $dir . '/' . $file;
try {
if (is_dir($path)) {
if (is_link($path)) {
// 符號連結到目錄:只刪連結
if (!unlink($path)) {
throw new RuntimeException("無法刪除符號連結: $path");
}
} else {
// 一般目錄:遞迴刪除
if (!$opts['followSymlinks'] && is_link($path)) {
unlink($path);
} else {
deleteDirectoryRecursive($path, $opts + ['maxDepth' => $opts['maxDepth']]);
}
}
} else {
// 檔案:嘗試修改權限後刪除
if (!is_writable($path)) {
@chmod($path, $opts['chmodFiles']);
}
if (!unlink($path)) {
throw new RuntimeException("無法刪除檔案: $path");
}
}
} catch (Throwable $e) {
$errors[] = $e->getMessage();
if (!$opts['continueOnError']) {
closedir($dh);
$depth--;
throw $e;
}
}
}
closedir($dh);
$depth--;
// 刪除目錄本身
if (!is_writable($dir)) {
@chmod($dir, $opts['chmodDirs']);
}
if (!rmdir($dir)) {
$error = error_get_last();
throw new RuntimeException("無法刪除目錄 $dir: " . ($error['message'] ?? '未知錯誤'));
}
if ($errors && $opts['continueOnError']) {
error_log("deleteDirectoryRecursive 部分失敗: " . implode('; ', $errors));
}
return true;
}
?>
<?php
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
function deleteDirectoryModern(string $dir): void {
if (!is_dir($dir)) return;
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST // 先刪子項再刪父目錄
);
foreach ($files as $file) {
if ($file->isDir()) {
rmdir($file->getPathname());
} else {
unlink($file->getPathname());
}
}
rmdir($dir);
}
// 使用
deleteDirectoryModern('./fakeDir');
?>
<?php
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
$fs = new Filesystem();
try {
$fs->remove(['/path/to/dir1', '/path/to/dir2']);
} catch (IOExceptionInterface $e) {
echo "刪除失敗: " . $e->getPath();
}
?>
| 風險 | 防護措施 |
|---|---|
| 路徑遍歷攻擊 (../../../etc) | realpath() 正規化、限制在允許根目錄下 |
| 刪除系統關鍵目錄 | 白名單驗證、禁止刪除 /、/var、/etc 等 |
| 符號連結攻擊 | 預設不跟隨符號連結、檢查 is_link() |
| 權限不足導致部分刪除 | 嘗試 chmod、記錄錯誤、選擇性繼續 |
| 併發刪除衝突 | 檔案鎖、或接受冪等失敗 |
| 無限遞迴(循環符號連結) | maxDepth 限制、追蹤已訪問 inode |