萬盛學電腦網

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

PHP 檔案下載控制器:遠端/本地雙模式、中文檔名編碼、安全路徑驗證完整實作

雙模式下載邏輯

<?php
function downloadFile(string $fileurl, int $forceDownload = 1): void {
    // 1. 遠端檔案:直接 302 導向
    if (strpos($fileurl, ':/') !== false) {
        header("Location: $fileurl");
        exit;
    }
    
    // 2. 本地檔案處理
    if ($forceDownload === 0) {
        // 直接導向站內 URL
        header("Location: " . SITE_URL . $fileurl);
        exit;
    }
    
    // 強制下載模式
    // 解析實體路徑 (防止目錄遍歷)
    $realPath = file_exists($fileurl) ? $fileurl : PHPCMS_ROOT . $fileurl;
    $realPath = realpath($realPath);
    
    // 安全檢查:必須在允許目錄內
    $allowedBase = realpath(PHPCMS_ROOT . 'upload/');
    if ($realPath === false || strpos($realPath, $allowedBase) !== 0) {
        header('HTTP/1.1 403 Forbidden');
        exit('非法檔案路徑');
    }
    
    if (!is_file($realPath) || !is_readable($realPath)) {
        header('HTTP/1.1 404 Not Found');
        exit('檔案不存在或不可讀');
    }
    
    $filename = basename($realPath);
    
    // 3. 中文檔名編碼處理 (RFC 5987 / RFC 6266)
    if (preg_match('/[\x80-\xFF]/', $filename)) {
        // 現代瀏覽器支援 UTF-8 編碼檔名
        $encodedName = rawurlencode($filename);
        header("Content-Disposition: attachment; filename*=UTF-8''{$encodedName}");
        // 兼容舊瀏覽器 (IE) 提供 fallback
        header("Content-Disposition: attachment; filename=\"{$encodedName}\"");
    } else {
        header("Content-Disposition: attachment; filename=\"{$filename}\"");
    }
    
    // 4. 輸出檔案
    header('Content-Type: application/octet-stream');
    header('Content-Length: ' . filesize($realPath));
    header('Content-Transfer-Encoding: binary');
    header('Accept-Ranges: bytes'); // 支援斷點續傳
    header('Cache-Control: private, must-revalidate');
    header('Pragma: private');
    header('Expires: 0');
    
    readfile($realPath); // 直接輸出,不佔用 PHP 記憶體
    exit;
}
?>

關鍵安全與相容性要點

  1. 路徑穿透防護: realpath() 解析真實路徑 + strpos($real, $base) === 0 確保在允許目錄樹下。
  2. 中文檔名: 採用 filename*=UTF-8''... (RFC 5987) 為主,舊式 filename="..." 為備援。
  3. 大檔案支援: 使用 readfile() 而非 file_get_contents() + echo,避免記憶體爆炸;配合 Accept-Ranges 支援續傳。
  4. MIME 偵測: 生產環境建議用 finfo_file() 偵測真實 MIME 類型,而非統一 octet-stream。
  5. 權限控管: 下載前驗證使用者權限 (登入狀態、購買記錄、下載次數限制等)。

Nginx X-Accel-Redirect / Apache X-Sendfile 高效能模式

將檔案讀取交給 Web Server,PHP 僅驗權並發送 Header:

<?php
// Nginx 配置需在 location 設定 internal 路徑
header('X-Accel-Redirect: /protected-files/' . $relativePath);
header('Content-Disposition: attachment; filename*=UTF-8\'\'' . rawurlencode($filename));
header('Content-Type: application/octet-stream');
exit;
?>

優點:PHP 進程立即釋放、支援 sendfile 系統呼叫、高併發下載不阻塞 PHP-FPM。

copyright © 萬盛學電腦網 all rights reserved