萬盛學電腦網

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

PHP 采集遠程圖片完整解決方案:破解防盜鏈、批量下載

業務場景

采集第三方站點內容時,圖片常設有防盜鏈(Referer 檢查),直接引用外鏈會顯示 403 或預設圖。解決方案:後端下載圖片至自有伺服器,再使用本地路徑。

核心流程

  1. 取得目標圖片 URL(正則解析頁面或 API 回傳)
  2. 發送 HTTP 請求讀取圖片二進制內容(需模擬 Referer/User-Agent)
  3. 建立儲存目錄、生成檔名(保留原名或雜湊命名)
  4. 寫入檔案,回傳本地路徑供後續使用

模組化函數實作

<?php
/** 建立可寫目錄 */
function make_dir(string $path): bool {
    if (!file_exists($path)) {
        mkdir($path, 0777, true);
        chmod($path, 0777);
    }
    return true;
}

/** 讀取遠程/本地檔案內容 */
function read_filetext(string $filepath): string {
    $filepath = trim($filepath);
    $fp = @fopen($filepath, 'rb');
    if (!$fp) return '';
    $content = '';
    if (strpos($filepath, '://') !== false) {
        // 遠程:分塊讀取
        while (!feof($fp)) {
            $content .= fread($fp, 8192);
        }
    } else {
        // 本地:一次讀取
        $content = fread($fp, filesize($filepath));
    }
    fclose($fp);
    return $content;
}

/** 寫入檔案 */
function write_filetext(string $filepath, string $content): bool {
    $fp = @fopen($filepath, 'wb');
    if (!$fp) return false;
    fwrite($fp, $content);
    fclose($fp);
    return true;
}

/** 從 URL 提取檔名 */
function get_filename(string $url): string {
    $parts = parse_url($url);
    $path = $parts['path'] ?? '';
    return basename($path);
}

/** 綜合下載入口 */
function save_pic(string $url, string $savepath = 'images/'): string {
    $url = str_replace(' ', '%20', trim($url));
    $content = read_filetext($url);
    if (empty($content)) die('無法讀取圖片: ' . $url);

    $filename = get_filename($url);
    make_dir($savepath);
    $filepath = rtrim($savepath, '/') . '/' . $filename;
    write_filetext($filepath, $content);
    return $filepath;
}
?>

批量采集範例

<?php
/** 從 HTML 內容提取所有 <img> src 並下載 */
function get_pic(string $html, string $saveDir): void {
    // 更健壯的正則:匹配 src 屬性值
    $pattern = '/<img[^>]+src=["\']([^"\']+)["\'][^>]*>/i';
    preg_match_all($pattern, $html, $matches);
    foreach ($matches[1] as $imgUrl) {
        $saved = save_pic($imgUrl, $saveDir);
        echo "[OK] $saved\n";
    }
}

// 實戰:采集某新聞頁圖片
$url = 'https://example.com/news/123.html';
$html = file_get_contents($url);
// 假設內容在 <div class="article">...</div>
if (preg_match('#<div class="article">(.*?)</div>#is', $html, $m)) {
    get_pic($m[1], 'collected_images/');
}
?>

進階挑戰與對策

挑戰對策
302 多次跳轉使用 cURL 並啟用 CURLOPT_FOLLOWLOCATION
防采集(IP 限流、驗證碼)代理池、降低頻率、模擬真實瀏覽器指紋
圖片經過 CDN 加密/簽名 URL分析簽名算法或改用無頭瀏覽器渲染後提取
大圖/超時設定連線/讀取超時、分塊寫入、支援斷點續傳

法律與道德提醒

采集前請確認目標站點 robots.txt、服務條款,尊重版權與爬蟲協議,避免對目標伺服器造成過大壓力。

copyright © 萬盛學電腦網 all rights reserved