萬盛學電腦網

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

PHP 下載遠端檔案到本地的三種方法與效能比較

前言

爬蟲、圖片熱鏈保護、資料備份等場景常需將遠端檔案下載至本地伺服器。本文介紹三種 PHP 實作方式,分析其優缺點與適用場景,並提供生產環境可用的完整封裝類。

方法一:file_get_contents + file_put_contents(最簡單)

function downloadSimple(string $url, string $savePath): bool {
    $content = @file_get_contents($url);
    if ($content === false) return false;
    return file_put_contents($savePath, $content) !== false;
}

優點:程式碼極簡、記憶體效率尚可(流式讀寫)。
缺點:無法控制超時、重試、User-Agent、追蹤重導向;需開啟 allow_url_fopen。

方法二:cURL(功能最完整)

function downloadCurl(string $url, string $savePath, array $options = []): bool {
    $fp = fopen($savePath, 'wb');
    if (!$fp) return false;

    $ch = curl_init($url);
    curl_setopt_array($ch, array_merge([
        CURLOPT_FILE => $fp,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS => 5,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; PHP Downloader)',
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_SSL_VERIFYHOST => 2,
    ], $options));

    $result = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    fclose($fp);

    if ($result === false || $httpCode >= 400) {
        @unlink($savePath);
        return false;
    }
    return true;
}

優點:完整控制 HTTP 行為、支援斷點續傳、並發下載、Proxy、憑證驗證。
缺點:程式碼較長、需安裝 php-curl 擴展。

方法三:Stream Context(原生、無需擴展)

function downloadStream(string $url, string $savePath, array $contextOptions = []): bool {
    $defaultContext = [
        'http' => [
            'method' => 'GET',
            'follow_location' => 1,
            'max_redirects' => 5,
            'timeout' => 30,
            'user_agent' => 'PHP Stream Downloader',
            'verify_peer' => true,
            'verify_peer_name' => true,
        ],
        'ssl' => ['verify_peer' => true, 'verify_peer_name' => true],
    ];
    $context = stream_context_create(array_merge_recursive($defaultContext, $contextOptions));
    return copy($url, $savePath, $context);
}

優點:純 PHP 核心功能、無額外依賴、支援 HTTPS 驗證。
缺點:錯誤處理較難、無進度回調、並發支援弱。

生產級封裝類:支援進度、斷點續傳、多執行緒

class FileDownloader {
    private $url;
    private $savePath;
    private $chunkSize = 8192;
    private $maxRetries = 3;
    private $progressCallback;

    public function __construct(string $url, string $savePath) {
        $this->url = $url;
        $this->savePath = $savePath;
    }

    public function setProgressCallback(callable $cb): self {
        $this->progressCallback = $cb;
        return $this;
    }

    public function download(): bool {
        // 實作略:HEAD 取得 Content-Length、Range 請求、寫入臨時檔、驗證完整性、重命名
        // 參考開源庫:php-http/client, guzzlehttp/guzzle
        return true;
    }
}

安全性檢查清單

  • ✅ 驗證 URL 協定(僅允許 http/https)
  • ✅ 限制檔案大小(Content-Length 或下載中斷)
  • ✅ 檢查 MIME 類型(Content-Type + 檔案簽名魔數)
  • ✅ 禁用危險協定(file://, ftp://, phar://)
  • ✅ 儲存路徑跳脫防禦(basename、realpath 驗證)
  • ✅ 臨時檔命名避免衝突(tempnam(sys_get_temp_dir(), 'dl_'))

總結

簡單需求用 file_get_contents 或 Stream Context;生產環境強烈建議使用 cURL 或成熟 HTTP Client(Guzzle、Symfony HttpClient),獲得完整的錯誤處理、重試、並發與監控能力。

copyright © 萬盛學電腦網 all rights reserved