首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 遞迴刪除目錄的兩種實作(含編碼處理)

     編輯:PHP 綜合知識

刪除非空目錄需遞迴清理檔案與子目錄。本文提供兩種寫法:標準 opendir/readdir 與 scandir 簡潔版,並說明 Windows 中文路徑編碼轉換關鍵點。

方法一:標準 opendir 遞迴

function recursiveDelete($dir) {
    if ($handle = @opendir($dir)) {
        while (($file = readdir($handle)) !== false) {
            if ($file === '.' || $file === '..') continue;
            $path = $dir . '/' . $file;
            if (is_dir($path)) {
                recursiveDelete($path); // 遞迴刪除子目錄
            } else {
                @unlink($path); // 刪除檔案
            }
        }
        @closedir($handle);
        @rmdir($dir); // 刪除空目錄
    }
}

方法二:scandir 簡潔版(推薦)

function my_del($path) {
    if (is_dir($path)) {
        $files = scandir($path);
        foreach ($files as $file) {
            if ($file === '.' || $file === '..') continue;
            my_del($path . '/' . $file);
        }
        @rmdir($path); // 此時目錄已空
    } else {
        @unlink($path);
    }
}

// 使用
$target = 'd:/技術文檔 - 副本';
// Windows + PHP UTF-8 腳本刪除中文路徑需轉碼
$target = iconv('UTF-8', 'GBK', $target); // 或 'CP950'/'BIG-5'
my_del($target);

關鍵差異對比

Windows 中文路徑編碼陷阱

  • PHP 腳本編碼通常為 UTF-8。
  • Windows 檔案系統 API 期望 GBK/CP950 編碼路徑。
  • 直接傳入 UTF-8 路徑會導致 is_dir/scandir 失敗(找不到路徑)。
  • 解決:iconv('UTF-8', 'GBK', $path) 或 mb_convert_encoding($path, 'GBK', 'UTF-8')。
  • Linux/macOS 檔案系統原生 UTF-8,**無需轉碼**。

現代替代:FilesystemIterator (PHP 5.3+)

function deleteDirModern($dir) {
    $files = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::CHILD_FIRST
    );
    foreach ($files as $file) {
        $file->isDir() ? rmdir($file->getPathname()) : unlink($file->getPathname());
    }
    rmdir($dir);
}
  • ✅ 物件導向、自動處理遞迴順序(CHILD_FIRST 先刪子項)。
  • ✅ 內建跳過 . ..。
  • ✅ 跨平台路徑處理較佳。

安全提醒

  • 生產環境**務必加入確認機制**(日誌、備份、軟刪除標記)。
  • 避免在 Web 根目錄執行刪除操作,防止誤刪核心檔案。
  • 大量檔案刪除建議加入 usleep() 降低 I/O 壓力。

根據專案 PHP 版本與跨平台需求選擇適合的實作,並務必處理 Windows 編碼問題。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
特性opendir/readdirscandir
程式碼行數較多極簡
記憶體逐個讀取,低一次載入所有檔名,大目錄較高
錯誤抑制各自 @統一 @
PHP 版本所有PHP 5+