采集第三方站點內容時,圖片常設有防盜鏈(Referer 檢查),直接引用外鏈會顯示 403 或預設圖。解決方案:後端下載圖片至自有伺服器,再使用本地路徑。
<?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、服務條款,尊重版權與爬蟲協議,避免對目標伺服器造成過大壓力。