刪除非空目錄是常見需求。本文整理三種 PHP 實作方式,分析優缺點與適用場景,附上可直接使用的函式代碼。
function deleteDir($dir) {
if (!is_dir($dir)) return false;
$items = scandir($dir);
foreach ($items as $item) {
if ($item === '.' || $item === '..') continue;
$path = $dir . DIRECTORY_SEPARATOR . $item;
is_dir($path) ? deleteDir($path) : unlink($path);
}
return rmdir($dir);
}
ini_set('xdebug.max_nesting_level', 500) 緩解)。function del_dir($dir) {
$dir = escapeshellarg($dir); // 必須跳脫防注入
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
return exec("rmdir /s /q {$dir}");
} else {
return exec("rm -rf {$dir}");
}
}
exec 權限、Windows/Linux 行為差異。function deltree($pathdir) {
if (!is_dir($pathdir)) return false;
$stack = [$pathdir];
while ($stack) {
$current = array_pop($stack);
$items = scandir($current);
foreach ($items as $item) {
if ($item === '.' || $item === '..') continue;
$path = $current . DIRECTORY_SEPARATOR . $item;
if (is_dir($path)) {
$stack[] = $path; // 目錄稍後處理
} else {
unlink($path); // 檔案立即刪除
}
}
// 子目錄清空後刪除目錄本身
@rmdir($current);
}
return true;
}
| 場景 | 推薦方法 | 理由 |
|---|---|---|
| 一般專案、中小目錄 | 方法一(遞迴) | 代碼簡潔、跨平台、易維護 |
| 超大目錄(百萬檔案以上) | 方法三(堆疊) | 避免堆疊溢位、記憶體可控 |
| 臨時清理、受控腳本 | 方法二(系統指令) | 速度最快,但需極謹慎使用 |
function is_empty_dir($dir) {
$handle = opendir($dir);
$count = 0;
while (($entry = readdir($handle)) !== false) {
if ($entry !== '.' && $entry !== '..') { $count++; break; }
}
closedir($handle);
return $count === 0;
}
實務上建議封裝為工具類,統一錯誤處理、日誌記錄與權限檢查,避免誤刪關鍵資料。