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

PHP 遞迴刪除非空目錄完整實作

     編輯:PHP 相關知識

核心遞迴演算法

進階版:支援符號連結、錯誤處理、回傳統計

 0, 'dirs' => 0, 'errors' => []];

    if (!is_dir($dir)) {
        $stats['errors'][] = "Not a directory: $dir";
        return $stats;
    }

    $handle = @opendir($dir);
    if (!$handle) {
        $stats['errors'][] = "Cannot open directory: $dir";
        return $stats;
    }

    while (($entry = @readdir($handle)) !== false) {
        if ($entry === '.' || $entry === '..') continue;

        $path = $dir . DIRECTORY_SEPARATOR . $entry;

        // 處理符號連結:只刪除連結本身,不遞迴目標
        if (is_link($path)) {
            if (@unlink($path)) $stats['files']++;
            else $stats['errors'][] = "Unlink symlink failed: $path";
            continue;
        }

        if (is_dir($path)) {
            $sub = removeDirAdvanced($path);
            $stats['files'] += $sub['files'];
            $stats['dirs'] += $sub['dirs'] + 1; // 含子目錄本身
            $stats['errors'] = array_merge($stats['errors'], $sub['errors']);
        } else {
            if (@unlink($path)) $stats['files']++;
            else $stats['errors'][] = "Unlink file failed: $path";
        }
    }

    closedir($handle);

    if (@rmdir($dir)) $stats['dirs']++;
    else $stats['errors'][] = "Rmdir failed: $dir";

    return $stats;
}

// 使用
$result = removeDirAdvanced('/tmp/test_dir');
echo "刪除檔案:{$result['files']},目錄:{$result['dirs']}";
if ($result['errors']) print_r($result['errors']);

FilesystemIterator 現代寫法(PHP 5.3+)

isDir()) {
            @rmdir($item->getPathname());
        } else {
            @unlink($item->getPathname());
        }
    }
    @rmdir($dir); // 最後刪除根目錄
}

權限與安全注意

  • 執行腳本的使用者需具備目錄/檔案 寫入與執行權限。
  • 避免刪除系統關鍵目錄,建議加入路徑白名單檢查。
  • 生產環境建議先移動至暫存區(rename()),確認無誤後再刪除。

結語

遞迴刪除非空目錄核心:opendir → readdir → is_dir 遞迴 / unlink → closedir → rmdir。現代專案推薦 RecursiveIteratorIterator::CHILD_FIRST 簡潔無誤。務必處理符號連結、權限錯誤、路徑安全,避免災難性誤刪。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved