刪除非空目錄需遞歸處理子目錄與檔案,關鍵點:
. 與 .. 避免無限遞歸unlink(),目錄用 rmdir()(需為空)<?php
/**
* 遞歸刪除目錄(傳統寫法)
* @param string $dir 目錄路徑
* @return bool 成功與否
*/
function recursiveDeleteV1(string $dir): bool
{
// 正規化路徑
$dir = rtrim($dir, '/\\');
if (!is_dir($dir)) {
return false; // 不存在或非目錄
}
$handle = @opendir($dir);
if ($handle === false) {
return false; // 權限不足
}
while (($entry = readdir($handle)) !== false) {
if ($entry === '.' || $entry === '..') continue;
$path = $dir . DIRECTORY_SEPARATOR . $entry;
if (is_dir($path)) {
// 遞歸刪除子目錄
if (!recursiveDeleteV1($path)) {
closedir($handle);
return false;
}
} else {
// 刪除檔案
if (!@unlink($path)) {
closedir($handle);
return false;
}
}
}
closedir($handle);
// 刪除空目錄本身
return @rmdir($dir);
}
?>
<?php
/**
* 遞歸刪除目錄(現代寫法)
* @param string $path 目錄或檔案路徑
* @return bool
*/
function recursiveDeleteV2(string $path): bool
{
$path = rtrim($path, '/\\');
if (!file_exists($path)) {
return true; // 不存在視為成功(冪等性)
}
if (is_file($path) || is_link($path)) {
return @unlink($path);
}
// 是目錄
$entries = @scandir($path);
if ($entries === false) {
return false; // 權限不足
}
foreach ($entries as $entry) {
if ($entry === '.' || $entry === '..') continue;
$fullPath = $path . DIRECTORY_SEPARATOR . $entry;
if (!recursiveDeleteV2($fullPath)) {
return false; // 任一失敗即回滾
}
}
return @rmdir($path);
}
?>
<?php
/**
* 使用 SPL 遞歸刪除(支援過濾、權限處理)
*/
function recursiveDeleteSPL(string $path): bool
{
$path = rtrim($path, '/\\');
if (!file_exists($path)) return true;
if (is_file($path) || is_link($path)) {
return @unlink($path);
}
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST // 關鍵:先處理子項,再處理父目錄
);
foreach ($iterator as $item) {
if ($item->isFile() || $item->isLink()) {
if (!@unlink($item->getPathname())) return false;
} elseif ($item->isDir()) {
if (!@rmdir($item->getPathname())) return false;
}
}
return @rmdir($path);
}
?>
<?php
/**
* 生產級遞歸刪除:含權限修復、符號連結保護、錯誤收集、執行時間保護
*/
function recursiveDeleteSafe(string $path, array &$errors = []): bool
{
$path = rtrim($path, '/\\');
$realPath = realpath($path);
// 防止刪除系統關鍵目錄
$protected = ['/', '/home', '/var', '/etc', '/usr', '/bin', '/sbin', '/root'];
if (in_array($realPath, $protected, true)) {
$errors[] = "受保護目錄不可刪除: $path";
return false;
}
if (!file_exists($path)) return true;
// 符號連結:只刪連結本身,不跟隨刪除目標
if (is_link($path)) {
return @unlink($path);
}
if (is_file($path)) {
// 嘗試修復權限再刪除
if (!is_writable($path)) @chmod($path, 0666);
return @unlink($path);
}
// 目錄
$entries = @scandir($path);
if ($entries === false) {
$errors[] = "無法讀取目錄 (權限不足): $path";
return false;
}
$success = true;
foreach ($entries as $entry) {
if ($entry === '.' || $entry === '..') continue;
$fullPath = $path . DIRECTORY_SEPARATOR . $entry;
if (!recursiveDeleteSafe($fullPath, $errors)) {
$success = false;
}
}
if ($success) {
if (!is_writable($path)) @chmod($path, 0777);
if (!@rmdir($path)) {
$errors[] = "無法刪除目錄: $path";
$success = false;
}
}
return $success;
}
// 使用
$errors = [];
if (recursiveDeleteSafe('/var/www/cache', $errors)) {
echo "刪除成功\n";
} else {
echo "刪除失敗:\n";
print_r($errors);
}
?>
<?php
// Windows + PHP 非 UTF-8 環境下,中文路徑需轉碼
$path = 'd:/技術文檔 - 副本';
if (PHP_OS_FAMILY === 'Windows') {
// 檢查腳本編碼,若為 UTF-8 需轉 GB2312/Big5
$path = iconv('UTF-8', 'GBK', $path);
}
recursiveDeleteSafe($path);
?>
| 方法 | PHP 版本 | 記憶體 | 速度 | 功能豐富度 |
|---|---|---|---|---|
| opendir 遞歸 | 4.0+ | 低 | 中 | 基礎 |
| scandir 遞歸 | 5.0+ | 中(載入全陣列) | 快 | 基礎 |
| SPL Iterator | 5.3+ | 低(迭代器) | 快 | 高(過濾、排序、權限) |
| 安全加強版 | 5.4+ | 低 | 中 | 最高(保護、錯誤收集、權限修復) |
DIRECTORY_SEPARATOR 跨平台相容@ 抑制警告,統一由回傳值判斷is_link(),避免誤刪連結目標set_time_limit(0) 與 memory_limit選對工具、加上防護,目錄刪除才不會變成「刪庫跑路」的開端。