萬盛學電腦網

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

PHP 遞迴刪除目錄與檔案:完整實作、錯誤處理與效能優化指南

核心函數:deldir() 完整版

<?php
/**
 * 遞迴刪除目錄及其所有內容
 *
 * @param string $dir  目錄路徑(相對或絕對)
 * @param bool   $skipErrors  遇錯誤是否跳過繼續(預設 false:拋出例外)
 * @return bool  成功刪除目錄本身回傳 true
 * @throws RuntimeException  失敗且 $skipErrors=false 時
 */
function deldir(string $dir, bool $skipErrors = false): bool
{
    // 正規化路徑:移除尾部斜線、解析符號連結
    $dir = rtrim(realpath($dir), DIRECTORY_SEPARATOR);
    if ($dir === false || !is_dir($dir)) {
        if ($skipErrors) return false;
        throw new \InvalidArgumentException("Directory not found: $dir");
    }

    // 開啟目錄控制代碼
    $dh = @opendir($dir);
    if (!$dh) {
        if ($skipErrors) return false;
        throw new \RuntimeException("Cannot open directory: $dir");
    }

    // 遍歷項目
    while (($file = readdir($dh)) !== false) {
        // 跳過 . 和 ..
        if ($file === '.' || $file === '..') continue;

        $fullPath = $dir . DIRECTORY_SEPARATOR . $file;

        // 符號連結特殊處理:刪除連結本身,不跟隨刪除目標
        if (is_link($fullPath)) {
            if (!@unlink($fullPath)) {
                if (!$skipErrors) throw new \RuntimeException("Failed to unlink symlink: $fullPath");
            }
            continue;
        }

        if (is_dir($fullPath)) {
            // 遞迴刪除子目錄
            if (!deldir($fullPath, $skipErrors)) {
                if (!$skipErrors) return false;
            }
        } else {
            // 刪除檔案
            if (!@unlink($fullPath)) {
                if (!$skipErrors) throw new \RuntimeException("Failed to delete file: $fullPath");
            }
        }
    }
    closedir($dh);

    // 最後刪除空目錄本身
    if (!@rmdir($dir)) {
        if (!$skipErrors) throw new \RuntimeException("Failed to remove directory: $dir");
        return false;
    }
    return true;
}

進階版:支援大量檔案、權限修正、進度回調

<?php
class DirectoryCleaner
{
    private int $deletedFiles = 0;
    private int $deletedDirs = 0;
    private int $errors = 0;
    private ?callable $progressCallback = null;

    public function setProgressCallback(callable $cb): self
    {
        $this->progressCallback = $cb;
        return $this;
    }

    public function delete(string $dir, bool $forcePermissions = true): bool
    {
        $this->resetCounters();
        $dir = rtrim(realpath($dir), DIRECTORY_SEPARATOR);
        if (!$dir || !is_dir($dir)) return false;

        $result = $this->deleteRecursive($dir, $forcePermissions);

        // 最後刪除根目錄
        if ($result && @rmdir($dir)) {
            $this->deletedDirs++;
            $this->reportProgress($dir, 'dir_deleted');
        }
        return $result;
    }

    private function deleteRecursive(string $path, bool $forcePermissions): bool
    {
        $dh = @opendir($path);
        if (!$dh) {
            $this->errors++;
            return false;
        }

        $success = true;
        while (($file = readdir($dh)) !== false) {
            if ($file === '.' || $file === '..') continue;

            $full = $path . DIRECTORY_SEPARATOR . $file;

            // 符號連結:只刪連結
            if (is_link($full)) {
                if (@unlink($full)) {
                    $this->deletedFiles++;
                    $this->reportProgress($full, 'file_deleted');
                } else {
                    $this->errors++;
                }
                continue;
            }

            if (is_dir($full)) {
                if ($this->deleteRecursive($full, $forcePermissions)) {
                    if (@rmdir($full)) {
                        $this->deletedDirs++;
                        $this->reportProgress($full, 'dir_deleted');
                    } else {
                        $this->errors++;
                        $success = false;
                    }
                } else {
                    $success = false;
                }
            } else {
                // 檔案:必要時修正權限再刪除
                if ($forcePermissions && !is_writable($full)) {
                    @chmod($full, 0644);
                }
                if (@unlink($full)) {
                    $this->deletedFiles++;
                    $this->reportProgress($full, 'file_deleted');
                } else {
                    $this->errors++;
                    $success = false;
                }
            }
        }
        closedir($dh);
        return $success;
    }

    private function reportProgress(string $path, string $action): void
    {
        if ($this->progressCallback) {
            ($this->progressCallback)($path, $action, $this->deletedFiles, $this->deletedDirs, $this->errors);
        }
    }

    private function resetCounters(): void
    {
        $this->deletedFiles = $this->deletedDirs = $this->errors = 0;
    }

    public function getStats(): array
    {
        return [
            'files_deleted' => $this->deletedFiles,
            'dirs_deleted' => $this->deletedDirs,
            'errors' => $this->errors,
        ];
    }
}

// 使用範例
$cleaner = new DirectoryCleaner();
$cleaner->setProgressCallback(function($path, $action, $files, $dirs, $errors) {
    static $last = 0;
    if (++$last % 100 === 0) {
        echo "\r已刪除: $files 檔案, $dirs 目錄, 錯誤: $errors";
    }
});

$ok = $cleaner->delete('/var/www/uploads/old_data');
echo "\n完成: " . json_encode($cleaner->getStats()) . "\n";

FilesystemIterator 現代寫法(PHP 5.3+)

<?php
function deleteDirectoryModern(string $dir): bool
{
    $dir = realpath($dir);
    if (!$dir || !is_dir($dir)) return false;

    $files = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::CHILD_FIRST // 關鍵:先處理子項目,再處理父目錄
    );

    foreach ($files as $file) {
        if ($file->isLink()) {
            @unlink($file->getPathname());
        } elseif ($file->isFile()) {
            @unlink($file->getPathname());
        } elseif ($file->isDir()) {
            @rmdir($file->getPathname());
        }
    }

    return @rmdir($dir);
}

優點: 程式碼極簡、自動處理遞迴順序、可搭配 FilesystemIterator::CURRENT_AS_FILEINFO 取得 SplFileInfo 物件。缺點: 錯誤處理較難自定義、大量檔案時記憶體佔用略高(迭代器需維護堆疊)。

效能優化建議

  1. 批次刪除: 系統呼叫開銷大,可考慮 exec('rm -rf ' . escapeshellarg($dir))(僅限受信環境、Linux/Unix)
  2. 非同步刪除: 將路徑推入佇列,背景 Worker 處理,避免阻塞 Web 請求
  3. 避開 NFS/網路磁碟: 本地 SSD 最快,網路檔案系統刪除極慢
  4. 大量小檔案: 考慮 tar -cf - dir | pv | gzip > archive.tar.gz 打包後再刪,減少 inode 操作

安全性檢查清單

  • [ ] 驗證 $dir 在允許範圍內(防止 ../../etc 路徑遍歷)
  • [ ] 確認目錄非系統關鍵目錄(/、/etc、/var/www 根目錄等)
  • [ ] 記錄審計日誌:誰、何時、刪除何路徑、結果
  • [ ] 生產環境啟用 skipErrors=false,失敗即拋出異常觸發告警
  • [ ] 備份機制:重要資料刪除前自動快照/備份

測試案例

<?php
// tests/DeleteDirectoryTest.php
use PHPUnit\Framework\TestCase;

class DeleteDirectoryTest extends TestCase
{
    private string $testBase;

    protected function setUp(): void
    {
        $this->testBase = sys_get_temp_dir() . '/deldir_test_' . uniqid();
        mkdir($this->testBase, 0755, true);
    }

    protected function tearDown(): void
    {
        // 清理測試殘留
        $this->safeDelete($this->testBase);
    }

    public function testDeleteSimpleDirectory(): void
    {
        $dir = $this->testBase . '/simple';
        mkdir($dir);
        file_put_contents($dir . '/a.txt', 'a');
        file_put_contents($dir . '/b.txt', 'b');

        $this->assertTrue(deldir($dir));
        $this->assertFalse(is_dir($dir));
    }

    public function testDeleteNestedDirectory(): void
    {
        $dir = $this->testBase . '/nested';
        mkdir($dir . '/level1/level2', 0755, true);
        file_put_contents($dir . '/level1/level2/deep.txt', 'deep');
        file_put_contents($dir . '/top.txt', 'top');

        $this->assertTrue(deldir($dir));
        $this->assertFalse(is_dir($dir));
    }

    public function testSkipErrors(): void
    {
        $dir = $this->testBase . '/skip';
        mkdir($dir);
        file_put_contents($dir . '/readonly.txt', 'x');
        chmod($dir . '/readonly.txt', 0444); // 唯讀

        // 預設模式會拋出例外
        $this->expectException(RuntimeException::class);
        deldir($dir);

        // skipErrors=true 應跳過唯讀檔案並刪除目錄
        $this->assertTrue(deldir($dir, true));
    }

    public function testSymlinkNotFollowed(): void
    {
        $dir = $this->testBase . '/symlink_test';
        mkdir($dir);
        $target = $dir . '/target.txt';
        file_put_contents($target, 'target');
        $link = $dir . '/link.txt';
        symlink($target, $link);

        $this->assertTrue(deldir($dir));
        // 目標檔案應保留
        $this->assertTrue(file_exists($target));
        $this->assertFalse(file_exists($link));
    }

    private function safeDelete(string $path): void
    {
        if (!is_dir($path)) return;
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );
        foreach ($files as $f) {
            $f->isDir() ? @rmdir($f->getPathname()) : @unlink($f->getPathname());
        }
        @rmdir($path);
    }
}

總結

PHP 刪除目錄看似簡單,實則涉及遞迴順序、符號連結處理、權限修正、錯誤恢復、進度回報、安全邊界。基礎版 deldir() 適合簡單腳本;生產環境建議使用 DirectoryCleaner 類別,提供統計、回調、權限強制、錯誤隔離。現代專案可優先考慮 RecursiveIteratorIterator::CHILD_FIRST 簡潔寫法,或委派給系統 rm -rf(嚴格管控參數)。核心原則:先刪內容、再刪目錄、符號連結不跟隨、失敗可追蹤。

copyright © 萬盛學電腦網 all rights reserved