PHP 內建 rmdir() 只能刪除**空目錄**。刪除包含文件/子目錄的非空目錄,需遞歸遍歷刪除文件後再刪除目錄。本文提供三種成熟度遞增的實現方案:基礎遞歸函數、僅刪除文件保留目錄結構、增強版帶錯誤處理與符號鏈接保護。
<?php
/**
* 遞歸刪除目錄及其所有內容(文件+子目錄)
* @param string $dirPath 目錄絕對路徑
* @return bool 成功返回 true,失敗拋出異常
*/
function deleteDirectory(string $dirPath): bool {
// 1. 規範化路徑
$dirPath = rtrim(realpath($dirPath), DIRECTORY_SEPARATOR);
if ($dirPath === false || !is_dir($dirPath)) {
throw new InvalidArgumentException("目錄不存在: $dirPath");
}
// 2. 打開目錄句柄
$handle = opendir($dirPath);
if ($handle === false) {
throw new RuntimeException("無法打開目錄: $dirPath");
}
try {
// 3. 遍歷條目
while (($item = readdir($handle)) !== false) {
// 跳過 . 和 ..
if ($item === '.' || $item === '..') continue;
$itemPath = $dirPath . DIRECTORY_SEPARATOR . $item;
// 4. 遞歸處理子目錄,直接刪除文件
if (is_dir($itemPath)) {
deleteDirectory($itemPath); // 遞歸
} else {
if (!unlink($itemPath)) {
throw new RuntimeException("刪除文件失敗: $itemPath");
}
}
}
} finally {
closedir($handle); // 確保關閉句柄
}
// 5. 刪除當前空目錄
if (!rmdir($dirPath)) {
throw new RuntimeException("刪除目錄失敗: $dirPath");
}
return true;
}
// 使用
try {
deleteDirectory('/var/www/cache/temp');
echo "刪除成功";
} catch (Exception $e) {
echo "刪除失敗: " . $e->getMessage();
}
?>
<?php
/**
* 遞歸刪除目錄下所有文件,保留目錄結構
* @param string $dirPath 目錄路徑
* @return int 刪除的文件數
*/
function deleteFilesOnly(string $dirPath): int {
$dirPath = rtrim(realpath($dirPath), DIRECTORY_SEPARATOR);
if (!$dirPath || !is_dir($dirPath)) {
throw new InvalidArgumentException("目錄不存在: $dirPath");
}
$count = 0;
$handle = opendir($dirPath);
if (!$handle) throw new RuntimeException("無法打開目錄: $dirPath");
try {
while (($item = readdir($handle)) !== false) {
if ($item === '.' || $item === '..') continue;
$itemPath = $dirPath . DIRECTORY_SEPARATOR . $item;
if (is_dir($itemPath)) {
$count += deleteFilesOnly($itemPath); // 遞歸清空子目錄
} else {
if (unlink($itemPath)) $count++;
}
}
} finally {
closedir($handle);
}
return $count;
}
// 使用:清空緩存目錄但保留目錄結構
$deleted = deleteFilesOnly('/var/www/cache');
echo "已刪除 $deleted 個文件";
?>
<?php
/**
* 生產級目錄刪除器
* 特性:
* - 使用 RecursiveDirectoryIterator + RecursiveIteratorIterator (SPL) 避免手動遞歸
* - 子優先遍歷,自動處理深層嵌套
* - 識別並跳過符號鏈接(不刪除鏈接目標)
* - 詳細錯誤收集而非拋出異常中斷
* - 支持進度回調
*/
class DirectoryDeleter {
private array $errors = [];
private int $deletedFiles = 0;
private int $deletedDirs = 0;
private ?callable $progressCallback = null;
public function __construct(?callable $progressCallback = null) {
$this->progressCallback = $progressCallback;
}
public function delete(string $dirPath): bool {
$this->resetCounters();
$dirPath = rtrim(realpath($dirPath), DIRECTORY_SEPARATOR);
if (!$dirPath || !is_dir($dirPath)) {
$this->errors[] = "目錄不存在: $dirPath";
return false;
}
// SPL 遞歸迭代器:CHILD_FIRST 先處理子項,再處理父目錄
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dirPath, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($iterator as $item) {
$path = $item->getPathname();
// 符號鏈接保護:不跟隨鏈接刪除目標,僅刪除鏈接文件本身
if ($item->isLink()) {
$this->doUnlink($path, 'link');
continue;
}
if ($item->isFile()) {
$this->doUnlink($path, 'file');
} elseif ($item->isDir()) {
$this->doRmdir($path);
}
$this->reportProgress($path);
}
// 最後刪除根目錄本身
$this->doRmdir($dirPath);
return empty($this->errors);
}
private function doUnlink(string $path, string $type): void {
if (@unlink($path)) {
$this->deletedFiles++;
} else {
$this->errors[] = "刪除{$type}失敗 (權限/鎖定/不存在): $path";
}
}
private function doRmdir(string $path): void {
if (@rmdir($path)) {
$this->deletedDirs++;
} else {
$this->errors[] = "刪除目錄失敗 (非空/權限/掛載點): $path";
}
}
private function reportProgress(string $path): void {
if ($this->progressCallback) {
($this->progressCallback)($path, $this->deletedFiles, $this->deletedDirs);
}
}
private function resetCounters(): void {
$this->errors = [];
$this->deletedFiles = 0;
$this->deletedDirs = 0;
}
public function getErrors(): array { return $this->errors; }
public function getDeletedFiles(): int { return $this->deletedFiles; }
public function getDeletedDirs(): int { return $this->deletedDirs; }
}
// 使用
$deleter = new DirectoryDeleter(function($path, $files, $dirs) {
echo "[進度] 已處理: $path (文件:$files, 目錄:$dirs)\n";
});
$success = $deleter->delete('/var/www/old_project');
if ($success) {
echo "✅ 完全刪除成功: 文件 {$deleter->getDeletedFiles()}, 目錄 {$deleter->getDeletedDirs()}\n";
} else {
echo "⚠️ 刪除完成但有錯誤:\n";
foreach ($deleter->getErrors() as $err) echo " - $err\n";
}
?>
| 方案 | 適用場景 | 優點 | 缺點 |
|---|---|---|---|
| 基礎遞歸函數 | 簡單腳本、一次性任務、目錄層級淺 | 代碼簡單、無依賴、易理解 | 深層遞歸可能棧溢出、無符號鏈接保護、錯誤處理弱 |
| 僅刪文件保留目錄 | 清空緩存/上傳/臨時目錄、保留結構 | 精確控制、安全 | 同上 |
| SPL 增強版 | 生產環境、深層目錄、大量文件、需審計日誌 | 無遞歸深度限制、符號鏈接安全、錯誤收集不中斷、進度回調 | 代碼較多、需 PHP 5.3+ |
realpath() 解析並確認在允許範圍內,防止 ../../etc/passwd 類路徑遍歷is_link() 檢測到鏈接時,**只刪鏈接文件本身**,絕不遞歸進入鏈接目標**(可能刪除系統關鍵目錄)rmdir() 失敗可能是掛載點、NFS 鎖定、權限不足,需記錄錯誤不中斷刪除非空目錄看似簡單,實則暗藏符號鏈接、掛載點、權限、深度遞歸等陷阱。**簡單任務用方案一/二,生產系統必上方案三(SPL + 錯誤收集 + 符號鏈接保護)**。記住:realpath() 是安全邊界,CHILD_FIRST 是遞歸順序保證,@ 抑制警告配合錯誤收集是健壯性基石。