rmdir(string $directory, ?resource $context = null): bool 僅能刪除空目錄。目錄內若有任何檔案或子目錄(含隱藏檔)會失敗並回傳 false。
<?php
$dir = "/tmp/test_dir";
if (file_exists($dir) && is_dir($dir)) {
if (rmdir($dir)) {
echo "目錄 {$dir} 已成功刪除。";
} else {
echo "刪除失敗:目錄非空或權限不足。";
}
} else {
echo "目錄不存在:{$dir}";
}
?>
| 原因 | 檢查方式 | 解決方法 |
|---|---|---|
| 目錄非空 | scandir($dir) 數量 > 2 | 先遞歸刪除內容(見下文) |
| 權限不足 | is_writable($dir) 為 false | 調整目錄擁有者/權限(chown/chmod) |
| 被程序佔用 | Linux: lsof +D $dir | 關閉佔用程序或重啟服務 |
| 掛載點/特殊檔案系統 | mount | grep $dir | 不可刪除,需先卸載 |
<?php
/**
* 安全刪除空目錄,支援多層級連續刪除
* @param string $dirPath 目標目錄
* @param bool $recursiveParents 是否連帶刪除上層空目錄
* @return array ['success' => bool, 'message' => string, 'deleted' => string[]]
*/
function removeEmptyDir(string $dirPath, bool $recursiveParents = false): array {
$dirPath = rtrim($dirPath, '/');
$deleted = [];
if (!is_dir($dirPath)) {
return ['success' => false, 'message' => "非目錄或不存在: {$dirPath}", 'deleted' => []];
}
// 檢查是否為空(排除 . 和 ..)
$contents = scandir($dirPath);
if (count($contents) > 2) {
return ['success' => false, 'message' => "目錄非空: {$dirPath}", 'deleted' => []];
}
// 嘗試刪除
if (@rmdir($dirPath)) {
$deleted[] = $dirPath;
// 遞歸檢查上層
if ($recursiveParents) {
$parent = dirname($dirPath);
if ($parent !== '/' && $parent !== '.') {
$parentResult = removeEmptyDir($parent, true);
$deleted = array_merge($deleted, $parentResult['deleted']);
}
}
return ['success' => true, 'message' => '刪除成功', 'deleted' => $deleted];
} else {
$error = error_get_last();
return ['success' => false, 'message' => "刪除失敗: " . ($error['message'] ?? '未知錯誤'), 'deleted' => []];
}
}
// 使用範例
$result = removeEmptyDir('/tmp/a/b/c', true);
if ($result['success']) {
echo "已刪除: " . implode(', ', $result['deleted']);
} else {
echo "錯誤: {$result['message']}";
}
?>
若需刪除非空目錄,請參考 遞歸刪除整個目錄 一文的完整實作。
DIRECTORY_SEPARATOR 或正斜線 /(PHP 自動轉換)。chmod($file, 0777)。掌握 rmdir() 行為邊界,配合 scandir()、is_writable() 預檢,能建立健壯的目錄清理功能。