網易 163 相簿對外部網站引用圖片設有 Referer 檢查,直接在 <img> 標籤使用圖片 URL 會顯示盜鏈提示。本文示範如何用 PHP Socket 模擬瀏覽器請求,代理取回圖片並輸出給前端。
<?php
ob_start();
$img = $_GET['url']; // 目標圖片完整 URL
// 解析主機與路徑
$host_path = str_replace('https://', '', $img);
$host = explode('/', $host_path)[0];
$path = strstr($host_path, '/');
// 建立 Socket 連線
$fp = fsockopen($host, 80, $errno, $errstr, 30);
if ($fp) {
// 發送偽造的 HTTP 請求標頭
fputs($fp, "GET $path HTTP/1.1\r\n");
fputs($fp, "Host: $host\r\n");
fputs($fp, "Accept: */*\r\n");
fputs($fp, "Referer: https://$host/\r\n"); // 關鍵:偽造 Referer
fputs($fp, "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)\r\n");
fputs($fp, "Connection: Close\r\n\r\n");
// 讀取回應
$content = '';
while ($str = fread($fp, 4096)) {
$content .= $str;
}
fclose($fp);
// 分離 HTTP 標頭與圖片二進制內容
$pos = strpos($content, "\r\n\r\n");
$image_data = substr($content, $pos + 4);
// 輸出圖片
header("Content-Type: image/jpeg");
echo $image_data;
}
?>
Referer 標頭,設為相簿首頁即可通過。fread 讀取原始回應,需手動切割 HTTP Header 與 Body。將上述程式碼存為 proxy_img.php,前端調用:
<img src="proxy_img.php?url=https://photo.163.com/xxx/xxx.jpg" />
ssl:// 協議與 443 埠)。