萬盛學電腦網

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

PHP 下載遠端圖片完整實作:偽造 Referer、Cookie、支援重定向與防盜鏈繞過

爬蟲、資料同步、圖片代理等場景需下載遠端圖片。目標站常設防盜鏈 (檢查 Referer)、要求登入 Cookie、或透過 302 重定向至 CDN。本文提供基於 Socket 底層協議的完整下載器,支援 Referer 偽造、Cookie 管理、重定向追蹤、超時控制、斷點續傳基礎。

核心下載類別:RemoteImageDownloader

<?php
class RemoteImageDownloader
{
    private $maxRedirects = 5;
    private $timeout = 30;
    private $userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36';

    /**
     * 下載圖片
     * @param string $imageUrl 圖片 URL
     * @param string $savePath 本地儲存路徑
     * @param string $referer 偽造 Referer (防盜鏈繞過)
     * @param string $cookie  Cookie 字串 (格式: "name=val; name2=val2")
     * @return bool 成功與否
     */
    public function download(string $imageUrl, string $savePath, string $referer = '', string $cookie = ''): bool {
        $urlInfo = $this->parseUrl($imageUrl);
        if (!$urlInfo) return false;

        $redirectCount = 0;
        $currentUrl = $imageUrl;
        $currentReferer = $referer ?: $imageUrl; // 預設用原 URL 做 Referer

        while ($redirectCount <= $this->maxRedirects) {
            $urlInfo = $this->parseUrl($currentUrl);
            if (!$urlInfo) return false;

            $fp = @fsockopen($urlInfo['host'], $urlInfo['port'], $errno, $errstr, $this->timeout);
            if (!$fp) return false;

            // 建構請求
            $request = "GET {$urlInfo['request_uri']} HTTP/1.1\r\n";
            $request .= "Host: {$urlInfo['host']}\r\n";
            $request .= "User-Agent: {$this->userAgent}\r\n";
            $request .= "Accept: image/webp,image/apng,image/*,*/*;q=0.8\r\n";
            $request .= "Referer: {$currentReferer}\r\n";
            if ($cookie) $request .= "Cookie: {$cookie}\r\n";
            $request .= "Connection: Close\r\n\r\n";

            fwrite($fp, $request);

            // 讀取回應標頭
            $headers = '';
            while (!feof($fp)) {
                $line = fgets($fp, 4096);
                $headers .= $line;
                if ($line === "\r\n" || $line === "\n") break;
            }

            // 解析狀態碼
            if (!preg_match('/HTTP\/\d\.\d\s+(\d{3})/', $headers, $m)) {
                fclose($fp); return false;
            }
            $status = (int)$m[1];

            // 解析 Content-Length
            $contentLength = 0;
            if (preg_match('/Content-Length:\s*(\d+)/i', $headers, $m)) {
                $contentLength = (int)$m[1];
            }

            // 處理重定向
            if ($status >= 300 && $status < 400) {
                if (preg_match('/Location:\s*(\S+)/i', $headers, $m)) {
                    $location = trim($m[1]);
                    // 處理相對 URL
                    if (strpos($location, 'http') !== 0) {
                        $location = $urlInfo['scheme'] . '://' . $urlInfo['host'] . 
                            (($location[0] === '/') ? '' : dirname($urlInfo['path']) . '/') . $location;
                    }
                    fclose($fp);
                    $currentUrl = $location;
                    $currentReferer = $currentUrl; // 重定向後 Referer 更新
                    $redirectCount++;
                    continue;
                }
            }

            // 非 2xx 視為失敗
            if ($status < 200 || $status >= 300) {
                fclose($fp); return false;
            }

            // 讀取 Body 並寫入檔案
            $outFp = @fopen($savePath, 'wb');
            if (!$outFp) { fclose($fp); return false; }

            $received = 0;
            $startTime = time();
            while (!feof($fp)) {
                $chunk = fread($fp, 8192);
                if ($chunk === '') break;
                fwrite($outFp, $chunk);
                $received += strlen($chunk);

                // 超時保護
                if (time() - $startTime > $this->timeout) break;
                // 長度滿足 (若有 Content-Length)
                if ($contentLength > 0 && $received >= $contentLength) break;
            }

            fclose($outFp);
            fclose($fp);

            // 驗證檔案大小
            if ($contentLength > 0 && $received < $contentLength) {
                @unlink($savePath);
                return false; // 下載不完整
            }

            return true; // 成功
        }
        return false; // 重定向過多
    }

    private function parseUrl(string $url): ?array {
        $url = trim($url);
        if (!preg_match('#^https?://#i', $url)) $url = 'https://' . $url;
        $parts = parse_url($url);
        if (!$parts || empty($parts['host'])) return null;
        return [
            'scheme'      => $parts['scheme'] ?? 'http',
            'host'        => $parts['host'],
            'port'        => $parts['port'] ?? ($parts['scheme'] === 'https' ? 443 : 80),
            'path'        => $parts['path'] ?? '/',
            'query'       => $parts['query'] ?? '',
            'request_uri' => ($parts['path'] ?? '/') . ($parts['query'] ? '?' . $parts['query'] : ''),
        ];
    }
}

使用範例

<?php
require 'RemoteImageDownloader.php';

$downloader = new RemoteImageDownloader();

// 1. 一般下載
$downloader->download('https://example.com/image.jpg', '/tmp/image.jpg');

// 2. 繞過防盜鏈:偽造 Referer 為首頁
$downloader->download(
    'https://cdn.example.com/photo.jpg',
    '/tmp/photo.jpg',
    'https://example.com/' // Referer
);

// 3. 攜帶登入 Cookie (需先登入取得 Cookie 字串)
$cookie = 'session_id=abc123; user_token=xyz789';
$downloader->download(
    'https://example.com/private/avatar.png',
    '/tmp/avatar.png',
    'https://example.com/profile',
    $cookie
);

// 4. 批次下載 (搭配 Generator 避免記憶體問題)
$urls = [
    'https://example.com/1.jpg',
    'https://example.com/2.jpg',
    // ...
];
foreach ($urls as $i => $url) {
    $path = "/tmp/img_{$i}.jpg";
    if ($downloader->download($url, $path)) {
        echo "✓ {$url}\n";
    } else {
        echo "✗ {$url}\n";
    }
    usleep(200000); // 禮貌延遲 0.2 秒
}

進階:cURL 版本 (更穩健、支援 HTTPS 驗證、Proxy、並發)

function downloadImageCurl(string $url, string $savePath, string $referer = '', string $cookie = ''): bool {
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL            => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS      => 5,
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_USERAGENT      => 'Mozilla/5.0 ...',
        CURLOPT_REFERER        => $referer ?: $url,
        CURLOPT_COOKIE         => $cookie,
        CURLOPT_SSL_VERIFYPEER => true,  // 生產環境務必開啟
        CURLOPT_SSL_VERIFYHOST => 2,
        CURLOPT_CAINFO         => '/etc/ssl/certs/ca-certificates.crt', // 系統 CA 憑證
        CURLOPT_WRITEFUNCTION  => function($ch, $data) use ($savePath) {
            static $fp = null;
            if ($fp === null) {
                $fp = fopen($savePath, 'wb');
                if (!$fp) return 0;
            }
            $written = fwrite($fp, $data);
            return $written;
        },
    ]);

    $result = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $errno = curl_errno($ch);
    curl_close($ch);

    // WRITEFUNCTION 回呼不返回 false 即視為成功寫入
    // 需額外檢查 HTTP 碼與檔案大小
    if ($errno !== 0 || $httpCode < 200 || $httpCode >= 300) {
        @unlink($savePath);
        return false;
    }
    return filesize($savePath) > 0;
}

防盜鏈繞過策略總結

防盜鏈類型繞過方法
Referer 檢查設定 `Referer` 為目標站首頁或上一頁
Cookie/Session 驗證先模擬登入取得 Cookie,下載時攜帶
User-Agent 檢查設定真實瀏覽器 UA
簽名/Token URL (帶過期時間)需逆向演算法或模擬瀏覽器完整流程獲取
IP 白名單使用代理 IP / 部署於允許 IP 的伺服器

法律與道德邊界

  • 尊重 `robots.txt`、`Terms of Service`、著作權法。
  • 僅下載公開授權或合法授權圖片。
  • 大量下載請聯繫站方申請 API 或資料授權。
  • 設定合理延遲 (`usleep`)、並發限制,避免對目標造成壓力。

Socket 版適合無 cURL 擴充環境、教學理解 HTTP 協議;生產環境強烈建議使用 cURL 版,功能完整、效能更好、支援 HTTP/2、TLS 1.3 等現代特性。

copyright © 萬盛學電腦網 all rights reserved