萬盛學電腦網

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

PHP 檔案下載處理完整指南:Header 設定、多檔下載、大檔支援、安全防護

基本單檔下載

<?php
$file = 'images/test.jpg';
$filename = 'testname.jpg';

if (!file_exists($file)) { http_response_code(404); exit('檔案不存在'); }

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . rawurlencode($filename) . '"');
header('Content-Length: ' . filesize($file));
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
readfile($file);
exit;

關鍵 Header 說明

Header用途
Content-Type: application/octet-stream強制瀏覽器下載而非開啟
Content-Disposition: attachment; filename="..."指定下載檔名,rawurlencode 處理中文
Content-Length顯示進度條、支援斷點續傳基礎
Cache-Control / Pragma避免代理快取干擾

大檔案支援:分塊輸出 + 斷點續傳 (HTTP 206)

function sendFile($path, $name = null) {
    if (!file_exists($path)) { http_response_code(404); return; }
    $name = $name ?? basename($path);
    $size = filesize($path);
    $mime = mime_content_type($path) ?: 'application/octet-stream';

    header('Content-Type: ' . $mime);
    header('Content-Disposition: attachment; filename="' . rawurlencode($name) . '"');
    header('Accept-Ranges: bytes');
    header('Content-Length: ' . $size);

    // 處理 Range 請求
    if (isset($_SERVER['HTTP_RANGE'])) {
        $range = $_SERVER['HTTP_RANGE'];
        if (preg_match('/bytes=(\d+)-(\d*)/', $range, $m)) {
            $start = (int)$m[1];
            $end = $m[2] ? (int)$m[2] : $size - 1;
            if ($start >= $size || $end >= $size) {
                header('HTTP/1.1 416 Range Not Satisfiable');
                header('Content-Range: bytes */' . $size);
                return;
            }
            header('HTTP/1.1 206 Partial Content');
            header('Content-Range: bytes ' . $start . '-' . $end . '/' . $size);
            header('Content-Length: ' . ($end - $start + 1));
            $fp = fopen($path, 'rb');
            fseek($fp, $start);
            while (!feof($fp) && ($pos = ftell($fp)) <= $end) {
                $chunk = min(8192, $end - $pos + 1);
                echo fread($fp, $chunk);
                @ob_flush(); @flush();
            }
            fclose($fp);
            return;
        }
    }

    // 完整檔案輸出
    $fp = fopen($path, 'rb');
    while (!feof($fp)) {
        echo fread($fp, 8192);
        @ob_flush(); @flush();
    }
    fclose($fp);
}

同時下載多檔:iframe / JS 方案

HTTP 回應只能有一個 Content-Disposition,無法單一請求推送多檔。

<!-- 方案一:隱藏 iframe -->
<iframe src="download.php?file=1.zip" style="display:none"></iframe>
<iframe src="download.php?file=2.zip" style="display:none"></iframe>

<!-- 方案二:JS 依序觸發 -->
<script>
['1.zip', '2.zip', '3.zip'].forEach(f => {
    var a = document.createElement('a');
    a.href = 'download.php?file=' + encodeURIComponent(f);
    a.style.display = 'none';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
});
</script>

安全防護清單

  • 路徑穿越防護:$file = realpath($baseDir . '/' . $input); if (strpos($file, $baseDir) !== 0) die('非法路徑');
  • 權限控管:驗證用戶登入、擁有權、下載次數限制。
  • MIME 偵測:使用 finfo_file 或 mime_content_type,勿信任副檔名。
  • 記憶體保護:大檔**必須**分塊輸出 (readfile 內部已分塊,但手動 fread 更可控),禁用 file_get_contents 載入整檔。
  • 速率限制:防止佔滿頻寬,可用 sleep() 或 Nginx limit_rate。
copyright © 萬盛學電腦網 all rights reserved