萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 遞歸刪除目錄完整指南:兩種實作模式與安全性加強

核心挑戰

刪除非空目錄需遞歸處理子目錄與檔案,關鍵點:

  1. 正確處理 . 與 .. 避免無限遞歸
  2. 檔案用 unlink(),目錄用 rmdir()(需為空)
  3. 權限不足、檔案被鎖定、符號連結等邊界情況
  4. 大量檔案時的記憶體與執行時間限制

方法一:傳統 opendir/readdir(相容舊版 PHP)

<?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);
}
?>

方法二:scandir + 現代寫法(更簡潔、PHP 5.4+)

<?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);
}
?>

方法三:SPL RecursiveDirectoryIterator(物件導向、功能最豐富)

<?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);
}
?>

中文路徑編碼問題(Windows 環境)

<?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 Iterator5.3+低(迭代器)快高(過濾、排序、權限)
安全加強版5.4+低中最高(保護、錯誤收集、權限修復)

最佳實踐清單

  • ✅ 使用 DIRECTORY_SEPARATOR 跨平台相容
  • ✅ @ 抑制警告,統一由回傳值判斷
  • ✅ 先檢查 is_link(),避免誤刪連結目標
  • ✅ 大量檔案前調大 set_time_limit(0) 與 memory_limit
  • ✅ 生產環境先備份、再刪除,或採用「軟刪除」標記
  • ✅ 關鍵目錄加入保護清單,防止誤刪

選對工具、加上防護,目錄刪除才不會變成「刪庫跑路」的開端。

copyright © 萬盛學電腦網 all rights reserved