萬盛學電腦網

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

PHP 遞迴刪除目錄完整實作:安全、高效、生產就緒版本

前言

遞迴刪除目錄需處理檔案、子目錄、權限、符號連結、錯誤處理等細節。本文提供生產環境可用的完整實作。

基礎版本(教學用)

<?php
function deleteDirectory(string $dir): bool {
    if (!is_dir($dir)) {
        return false;
    }
    
    $dh = opendir($dir);
    if (!$dh) {
        return false;
    }
    
    while (($file = readdir($dh)) !== false) {
        if ($file === '.' || $file === '..') continue;
        
        $path = $dir . '/' . $file;
        
        if (is_dir($path)) {
            deleteDirectory($path); // 遞迴刪除子目錄
        } else {
            unlink($path); // 刪除檔案
        }
    }
    
    closedir($dh);
    return rmdir($dir); // 刪除空目錄
}

$dir = "./fakeDir";
deleteDirectory($dir);
?>

生產級實作:錯誤處理、符號連結、權限、效能

<?php
/**
 * 安全遞迴刪除目錄
 * 
 * @param string $dir 目錄路徑
 * @param array $options 選項
 * @return bool 成功與否
 * @throws RuntimeException 關鍵錯誤
 */
function deleteDirectoryRecursive(string $dir, array $options = []): bool {
    $defaults = [
        'followSymlinks' => false,  // 是否跟隨符號連結刪除目標
        'continueOnError' => false, // 遇錯繼續或拋出例外
        'maxDepth' => 1000,         // 最大遞迴深度防無限迴圈
        'chmodFiles' => 0644,       // 刪除前嘗試修改檔案權限
        'chmodDirs' => 0755,        // 刪除前嘗試修改目錄權限
    ];
    $opts = array_merge($defaults, $options);
    
    // 正規化路徑
    $dir = rtrim($dir, '/\\');
    
    if (!file_exists($dir)) {
        return true; // 不存在視為成功(冪等性)
    }
    
    if (!is_dir($dir)) {
        throw new InvalidArgumentException("路徑非目錄: $dir");
    }
    
    // 檢查符號連結
    if (is_link($dir) && !$opts['followSymlinks']) {
        return unlink($dir); // 只刪除連結本身
    }
    
    // 遞迴深度保護
    static $depth = 0;
    if (++$depth > $opts['maxDepth']) {
        throw new RuntimeException("遞迴深度超過限制: $dir");
    }
    
    $dh = @opendir($dir);
    if (!$dh) {
        $error = error_get_last();
        throw new RuntimeException("無法開啟目錄 $dir: " . ($error['message'] ?? '未知錯誤'));
    }
    
    $errors = [];
    
    while (($file = readdir($dh)) !== false) {
        if ($file === '.' || $file === '..') continue;
        
        $path = $dir . '/' . $file;
        
        try {
            if (is_dir($path)) {
                if (is_link($path)) {
                    // 符號連結到目錄:只刪連結
                    if (!unlink($path)) {
                        throw new RuntimeException("無法刪除符號連結: $path");
                    }
                } else {
                    // 一般目錄:遞迴刪除
                    if (!$opts['followSymlinks'] && is_link($path)) {
                        unlink($path);
                    } else {
                        deleteDirectoryRecursive($path, $opts + ['maxDepth' => $opts['maxDepth']]);
                    }
                }
            } else {
                // 檔案:嘗試修改權限後刪除
                if (!is_writable($path)) {
                    @chmod($path, $opts['chmodFiles']);
                }
                if (!unlink($path)) {
                    throw new RuntimeException("無法刪除檔案: $path");
                }
            }
        } catch (Throwable $e) {
            $errors[] = $e->getMessage();
            if (!$opts['continueOnError']) {
                closedir($dh);
                $depth--;
                throw $e;
            }
        }
    }
    
    closedir($dh);
    $depth--;
    
    // 刪除目錄本身
    if (!is_writable($dir)) {
        @chmod($dir, $opts['chmodDirs']);
    }
    
    if (!rmdir($dir)) {
        $error = error_get_last();
        throw new RuntimeException("無法刪除目錄 $dir: " . ($error['message'] ?? '未知錯誤'));
    }
    
    if ($errors && $opts['continueOnError']) {
        error_log("deleteDirectoryRecursive 部分失敗: " . implode('; ', $errors));
    }
    
    return true;
}
?>

現代替代:FilesystemIterator (PHP 5.3+)

<?php
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;

function deleteDirectoryModern(string $dir): void {
    if (!is_dir($dir)) return;
    
    $files = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::CHILD_FIRST // 先刪子項再刪父目錄
    );
    
    foreach ($files as $file) {
        if ($file->isDir()) {
            rmdir($file->getPathname());
        } else {
            unlink($file->getPathname());
        }
    }
    
    rmdir($dir);
}

// 使用
deleteDirectoryModern('./fakeDir');
?>

Symfony Filesystem 組件(企業級專案推薦)

<?php
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;

$fs = new Filesystem();

try {
    $fs->remove(['/path/to/dir1', '/path/to/dir2']);
} catch (IOExceptionInterface $e) {
    echo "刪除失敗: " . $e->getPath();
}
?>

安全性檢查清單

安全封裝範例

<?php
class SafeDirectoryRemover {
    private array $allowedRoots = [];
    
    public function __construct(array $allowedRoots) {
        $this->allowedRoots = array_map(fn($p) => realpath($p), $allowedRoots);
    }
    
    public function delete(string $targetDir): bool {
        $realTarget = realpath($targetDir);
        
        // 驗證在允許根目錄下
        $allowed = false;
        foreach ($this->allowedRoots as $root) {
            if (str_starts_with($realTarget, $root)) {
                $allowed = true;
                break;
            }
        }
        if (!$allowed) {
            throw new SecurityException("嘗試刪除非授權目錄: $targetDir");
        }
        
        // 禁止刪除根目錄本身
        if (in_array($realTarget, $this->allowedRoots, true)) {
            throw new SecurityException("禁止刪除根目錄: $targetDir");
        }
        
        return deleteDirectoryRecursive($realTarget, ['continueOnError' => true]);
    }
}

// 使用
$remover = new SafeDirectoryRemover(['/var/www/uploads', '/tmp/app']);
$remover->delete('/var/www/uploads/user_123/temp');
?>

效能優化建議

  • 大量檔案:考慮 exec('rm -rf ' . escapeshellarg($dir))(需評估安全性)
  • 網路檔案系統(NFS/S3):避免遞迴,使用批次刪除 API
  • 定期清理:搭配 cron + find -mtime +30 -delete
  • 軟刪除:標記 deleted_at,背景任務真正刪除

總結

  • 基礎版:教學理解遞迴邏輯,不可直接用於生產
  • 生產版:錯誤處理、符號連結、權限、深度限制、冪等性、安全驗證
  • 現代專案:優先用 RecursiveIteratorIterator 或 Symfony Filesystem
  • 安全第一:路徑白名單、禁止刪除根目錄、符號連結保護
  • 測試覆蓋:空目錄、巢狀目錄、符號連結、無權限檔案、不存在路徑、循環連結
copyright © 萬盛學電腦網 all rights reserved
風險防護措施
路徑遍歷攻擊 (../../../etc)realpath() 正規化、限制在允許根目錄下
刪除系統關鍵目錄白名單驗證、禁止刪除 /、/var、/etc 等
符號連結攻擊預設不跟隨符號連結、檢查 is_link()
權限不足導致部分刪除嘗試 chmod、記錄錯誤、選擇性繼續
併發刪除衝突檔案鎖、或接受冪等失敗
無限遞迴(循環符號連結)maxDepth 限制、追蹤已訪問 inode