萬盛學電腦網

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

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

核心邏輯

刪除非空目錄需遞迴處理:先刪除子檔案/子目錄,最後刪除空目錄本身。

標準實作

<?php
/**
 * 遞迴刪除目錄及其所有內容
 * 
 * @param string $dirPath 目錄路徑
 * @return bool 成功刪除回傳 true
 */
function removeDir(string $dirPath): bool {
    // 1. 驗證是否為目錄
    if (!is_dir($dirPath)) {
        return false;
    }
    
    // 2. 開啟目錄控制代碼
    $handle = @opendir($dirPath);
    if ($handle === false) {
        return false; // 權限不足等
    }
    
    // 3. 遍歷目錄項目
    while (($item = readdir($handle)) !== false) {
        // 跳過 . 和 ..
        if ($item === '.' || $item === '..') {
            continue;
        }
        
        $fullPath = $dirPath . DIRECTORY_SEPARATOR . $item;
        
        // 4. 遞迴處理:目錄則遞迴,檔案則刪除
        if (is_dir($fullPath)) {
            removeDir($fullPath);
        } else {
            @unlink($fullPath); // 抑制警告,由回傳值判斷
        }
    }
    
    // 5. 關閉目錄控制代碼
    closedir($handle);
    
    // 6. 刪除現在已空的目錄
    return @rmdir($dirPath);
}
?>

使用範例

進階版:支援符號連結、錯誤收集、回呼

errors = [];
        $this->deletedFiles = $this->deletedDirs = 0;
        return $this->doRemove($path, $progress);
    }
    
    private function doRemove(string $path, callable $progress): bool {
        if (is_link($path)) {
            // 符號連結:只刪除連結本身,不跟隨
            $result = @unlink($path);
            if ($result) $this->deletedFiles++;
            return $result;
        }
        
        if (!is_dir($path)) {
            $result = @unlink($path);
            if ($result) $this->deletedFiles++;
            if ($progress) $progress($path, 'file', $result);
            return $result;
        }
        
        $handle = @opendir($path);
        if (!$handle) {
            $this->errors[] = "無法開啟目錄: $path";
            return false;
        }
        
        $success = true;
        while (($item = readdir($handle)) !== false) {
            if ($item === '.' || $item === '..') continue;
            $fullPath = $path . DIRECTORY_SEPARATOR . $item;
            $success &= $this->doRemove($fullPath, $progress);
        }
        closedir($handle);
        
        $result = @rmdir($path);
        if ($result) $this->deletedDirs++;
        if ($progress) $progress($path, 'dir', $result);
        return $success;
    }
    
    public function getStats(): array {
        return [
            'files' => $this->deletedFiles,
            'dirs' => $this->deletedDirs,
            'errors' => $this->errors,
        ];
    }
}

// 使用
$remover = new DirectoryRemover();
$remover->remove('/var/www/cache', function($path, $type, $ok) {
    echo "[$type] $path : " . ($ok ? 'OK' : 'FAIL') . "\n";
});
print_r($remover->getStats());

FilesystemIterator 現代寫法 (PHP 5.3+)

isDir()) {
            removeDirModern($item->getPathname());
        } else {
            @unlink($item->getPathname());
        }
    }
    return @rmdir($dir);
}

權限與安全注意事項

  • 執行腳本的使用者需擁有目錄寫入/執行權限
  • 避免刪除系統關鍵目錄(加入路徑白名單檢查)
  • 生產環境建議先備份或採用軟刪除(移至回收桶目錄)
  • 大量檔案刪除考慮分批處理,避免超時

單行指令替代方案 (Linux)

警告: 僅限受信任環境,必須嚴格驗證路徑防止命令注入。

copyright © 萬盛學電腦網 all rights reserved