萬盛學電腦網

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

PHP 遠端下載檔案到本地完整實作:cURL 優先、斷點續傳、大檔案支援、錯誤處理

需求場景

  • 采集器抓取圖片/文件
  • 遷移舊系統附件
  • 定時備份遠端資源
  • 用戶上傳前預覽/驗證遠端檔案

核心選擇:cURL vs file_get_contents vs stream_copy_to_stream

特性cURL (推薦)stream_context + copyfile_get_contents
大檔案記憶體✅ 串流寫入檔案✅ 串流❌ 全讀入記憶體
斷點續傳✅ 原生支援 Range✅ 可手工實現❌
超時控制✅ 連線/總超時分離✅ stream timeout❌ 只能靠 ini_set
重定向/HTTPS/認證✅ 完整支援⚠️ 基礎支援⚠️ 基礎支援
進度回調✅ CURLOPT_PROGRESSFUNCTION❌❌
效能⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐

生產級下載器類實作

<?php
declare(strict_types=1);

namespace App\Utility;

use RuntimeException;

/**
 * 遠端檔案下載器
 * 特性:cURL 優先、自動建立目錄、斷點續傳、進度回調、完整性驗證、臨時檔原子重命名
 */
final class RemoteFileDownloader
{
    private int $connectTimeout;
    private int $timeout;
    private int $maxRedirects;
    private string $userAgent;
    private ?callable $progressCallback;

    public function __construct(
        int $connectTimeout = 10,
        int $timeout = 300,
        int $maxRedirects = 5,
        string $userAgent = 'Mozilla/5.0 (PHP RemoteDownloader)'
    ) {
        $this->connectTimeout = $connectTimeout;
        $this->timeout = $timeout;
        $this->maxRedirects = $maxRedirects;
        $this->userAgent = $userAgent;
    }

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

    /**
     * 下載檔案
     *
     * @param string $url 遠端 URL
     * @param string $destPath 本地儲存路徑 (含檔名)
     * @param bool $resume 是否嘗試斷點續傳
     * @param string|null $expectedHash 預期 SHA256 雜湊 (驗證完整性)
     * @return array ['size' => int, 'hash' => string, 'resumed' => bool]
     * @throws RuntimeException
     */
    public function download(
        string $url,
        string $destPath,
        bool $resume = false,
        ?string $expectedHash = null
    ): array {
        // 1. 準備目錄
        $dir = dirname($destPath);
        if (!is_dir($dir)) {
            if (!mkdir($dir, 0755, true) && !is_dir($dir)) {
                throw new RuntimeException("無法建立目錄: $dir");
            }
        }

        // 2. 臨時檔路徑 (原子寫入:下載完成再 rename,避免部分檔案被讀取)
        $tempPath = $destPath . '.part';

        // 3. 斷點續傳:檢查現有臨時檔大小
        $resumeOffset = 0;
        if ($resume && is_file($tempPath)) {
            $resumeOffset = filesize($tempPath);
            if ($resumeOffset > 0) {
                $this->log("Resume download from byte $resumeOffset");
            }
        }

        // 4. 初始化 cURL
        if (!function_exists('curl_init')) {
            throw new RuntimeException('cURL extension required');
        }
        $ch = curl_init($url);
        $options = [
            CURLOPT_RETURNTRANSFER => false,      // 直接寫入檔案
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_MAXREDIRS      => $this->maxRedirects,
            CURLOPT_CONNECTTIMEOUT => $this->connectTimeout,
            CURLOPT_TIMEOUT        => $this->timeout,
            CURLOPT_SSL_VERIFYPEER => true,       // 生產環境強制驗證
            CURLOPT_USERAGENT      => $this->userAgent,
            CURLOPT_WRITEFUNCTION  => function ($ch, $data) use ($tempPath, &$resumeOffset) {
                // 寫入回調:追加模式寫入
                $fp = fopen($tempPath, 'ab');
                if (!$fp) return 0;
                $written = fwrite($fp, $data);
                fclose($fp);
                return $written;
            },
        ];

        // 斷點續傳:設定 Range 標頭
        if ($resumeOffset > 0) {
            $options[CURLOPT_RANGE] = $resumeOffset . '-';
            $options[CURLOPT_RESUME_FROM] = $resumeOffset; // 兼容舊版
        }

        // 進度回調
        if ($this->progressCallback) {
            $options[CURLOPT_NOPROGRESS] = false;
            $options[CURLOPT_PROGRESSFUNCTION] = function (
                $ch,
                $downloadTotal,
                $downloadNow,
                $uploadTotal,
                $uploadNow
            ) use ($resumeOffset) {
                ($this->progressCallback)(
                    $downloadTotal + $resumeOffset,
                    $downloadNow + $resumeOffset
                );
            };
        }

        curl_setopt_array($ch, $options);

        // 5. 開啟輸出檔案 (若不續傳則覆蓋)
        $fp = fopen($tempPath, $resumeOffset > 0 ? 'ab' : 'wb');
        if (!$fp) {
            curl_close($ch);
            throw new RuntimeException("無法開啟寫入檔案: $tempPath");
        }
        curl_setopt($ch, CURLOPT_FILE, $fp);

        // 6. 執行下載
        $result = curl_exec($ch);
        $errno = curl_errno($ch);
        $error = curl_error($ch);
        $info = curl_getinfo($ch);

        fclose($fp);
        curl_close($ch);

        // 7. 錯誤處理
        if ($errno !== 0) {
            @unlink($tempPath);
            throw new RuntimeException("cURL Error [$errno]: $error");
        }

        $httpCode = (int)($info['http_code'] ?? 0);
        if ($httpCode < 200 || $httpCode >= 300) {
            @unlink($tempPath);
            throw new RuntimeException("HTTP Error: $httpCode");
        }

        // 206 Partial Content 表示續傳成功
        $resumed = ($httpCode === 206);

        // 8. 完整性驗證
        $finalSize = filesize($tempPath);
        if ($finalSize === false || $finalSize === 0) {
            @unlink($tempPath);
            throw new RuntimeException('下載檔案為空');
        }

        if ($expectedHash) {
            $actualHash = hash_file('sha256', $tempPath);
            if (!hash_equals($expectedHash, $actualHash)) {
                @unlink($tempPath);
                throw new RuntimeException("雜湊驗證失敗: 期望 $expectedHash, 實際 $actualHash");
            }
        }

        // 9. 原子重命名:.part → 正式檔名 (同檔案系統瞬間完成)
        if (!rename($tempPath, $destPath)) {
            @unlink($tempPath);
            throw new RuntimeException("無法重命名檔案: $tempPath -> $destPath");
        }

        $this->log("Download complete: $destPath ($finalSize bytes)");

        return [
            'size'    => $finalSize,
            'hash'    => $expectedHash ?? hash_file('sha256', $destPath),
            'resumed' => $resumed,
        ];
    }

    private function log(string $msg): void
    {
        error_log(date('[Y-m-d H:i:s] ') . $msg);
    }
}

// ==================== 使用示範 ====================
require 'vendor/autoload.php';

$downloader = new \App\Utility\RemoteFileDownloader(
    connectTimeout: 10,
    timeout: 600, // 10 分鐘大檔超時
    maxRedirects: 3
);

// 可選:進度條回調
$downloader->setProgressCallback(function (int $total, int $downloaded) {
    if ($total > 0) {
        $pct = round($downloaded / $total * 100, 1);
        echo "\rProgress: {$pct}% ({$downloaded}/{$total} bytes)";
    }
});

try {
    $result = $downloader->download(
        url: 'https://releases.ubuntu.com/22.04.3/ubuntu-22.04.3-live-server-amd64.iso',
        destPath: '/var/www/downloads/ubuntu-22.04.iso',
        resume: true, // 支援斷點續傳
        expectedHash: 'a1b2c3d4...' // 可選:官方提供的 SHA256
    );
    echo "\n✅ 下載成功: {$result['size']} bytes, SHA256: {$result['hash']}";
} catch (RuntimeException $e) {
    echo "\n❌ 下載失敗: " . $e->getMessage();
}
?>

關鍵技術細節解析

1. 串流寫入 (CURLOPT_WRITEFUNCTION / CURLOPT_FILE)

不將下載內容緩存在記憶體,直接寫入檔案指標,**支援任意大小檔案 (GB/TB 級)**,記憶體佔用恆定極低。

2. 斷點續傳

  • 讀取 .part 臨時檔大小作為 Range: bytes=X-
  • 伺服器回 206 Partial Content 表示支援續傳
  • 若伺服器不支援 Range (回 200),cURL 會重頭下載,臨時檔會被覆蓋 (因 ab 模式配合 CURLOPT_RESUME_FROM 行為視實現而定,建議檢測 206 確認)

3. 原子寫入

下載至 .part 臨時檔,**完成後 rename() 替換目標檔**。同檔案系統下 rename 是原子操作,**讀取端永遠不會看到不完整檔案**。

4. 完整性驗證

下載完成後計算 hash_file('sha256') 比對預期值,**防止傳輸損壞、中間人竄改、來源端檔案已變更**。

5. 進度回調

CURLOPT_PROGRESSFUNCTION 提供即時下載進度,可構建 CLI 進度條、WebSocket 推送前端進度、記錄下載速度統計。

進階:並發下載多檔案 (cURL Multi)

function downloadMultiple(array $urls, string $destDir, int $concurrency = 5): array
{
    $mh = curl_multi_init();
    $handles = [];
    $results = [];
    $queue = $urls;

    // 初始化前 $concurrency 個
    for ($i = 0; $i < $concurrency && !empty($queue); $i++) {
        $url = array_shift($queue);
        $ch = curl_init($url);
        // ... 設定選項 (同上單檔) ...
        curl_multi_add_handle($mh, $ch);
        $handles[(int)$ch] = ['url' => $url, 'ch' => $ch, 'temp' => $destDir . '/' . basename($url) . '.part'];
    }

    $running = null;
    do {
        curl_multi_exec($mh, $running);
        curl_multi_select($mh, 0.1);

        // 檢查完成的
        while ($info = curl_multi_info_read($mh)) {
            $ch = $info['handle'];
            $data = $handles[(int)$ch];
            // 處理結果、重命名、錯誤處理...
            curl_multi_remove_handle($mh, $ch);
            curl_close($ch);
            unset($handles[(int)$ch]);

            // 補充新任務
            if (!empty($queue)) {
                $url = array_shift($queue);
                $newCh = curl_init($url);
                // ... 設定 ...
                curl_multi_add_handle($mh, $newCh);
                $handles[(int)$newCh] = ['url' => $url, 'ch' => $newCh, ...];
            }
        }
    } while ($running > 0);

    curl_multi_close($mh);
    return $results;
}

常見坑點與解決

問題原因解決
大檔案下載中斷/記憶體爆炸用 file_get_contents 或 CURLOPT_RETURNTRANSFER=true**必須用 CURLOPT_WRITEFUNCTION 或 CURLOPT_FILE 串流寫入檔案**
下載檔案損壞/不完整網路波動、伺服器中斷、無驗證啟用斷點續傳 + SHA256 雜湊驗證
SSL 憑證驗證失敗CURLOPT_SSL_VERIFYPEER=true 但無 CA 憑證配置 CURLOPT_CAINFO 指向 cacert.pem (定期更新)
檔名含中文/特殊字符亂碼URL 編碼、文件系統編碼不一致用 rawurldecode() 解碼 URL 檔名,或自定義安全檔名
權限拒絕無法寫入目錄擁有者/權限錯誤、open_basedir 限制檢查 PHP 進程用戶權限、php.ini open_basedir

結語

**遠端下載不是「撈個內容存起來」那麼簡單**。生產級下載器需具備:**串流寫入 (抗大檔)、斷點續傳 (抗中斷)、原子重命名 (抗併發讀取)、雜湊驗證 (抗竄改/損壞)、精細超時/重試/限速/進度回調 (可觀測性)**。本文提供的 RemoteFileDownloader 類已整合所有核心特性,**可直接投入生產環境**作為采集器、遷移工具、備份系統的核心下載引擎。

copyright © 萬盛學電腦網 all rights reserved