$_SERVER['HTTP_REFERER'] 記錄用戶從哪個頁面跳轉而來,常用於防盜鏈、統計來源、安全驗證。但它完全由客戶端控制,不可信任,極易偽造。理解偽造手法有助於構建更健壯的防禦邏輯。
$url = 'https://target.com/page.php';
$referer = 'https://fake-source.com/referrer-page';
$options = [
'http' => [
'method' => 'GET',
'header' => "Referer: $referer\r\n" .
"User-Agent: Mozilla/5.0 (compatible; PHP)\r\n",
'timeout' => 10
]
];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
if ($response === false) {
throw new Exception("請求失敗");
}
echo $response;
關鍵點:stream_context_create 允許自定義 HTTP 頭,Referer 即在 header 中設置。
$url = 'https://target.com/page.php';
$referer = 'https://fake-source.com/referrer-page';
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_REFERER => $referer, // 核心:設置 Referer
CURLOPT_RETURNTRANSFER => true, // 返回字符串而非直接輸出
CURLOPT_FOLLOWLOCATION => true, // 跟隨重定向
CURLOPT_MAXREDIRS => 5,
CURLOPT_TIMEOUT => 15,
CURLOPT_SSL_VERIFYPEER => false, // 開發環境忽略 SSL 驗證
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
]);
$response = curl_exec($ch);
if (curl_errno($ch)) {
throw new Exception("cURL 錯誤: " . curl_error($ch));
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo "HTTP 狀態: $httpCode\n";
echo $response;
優勢:支援 POST、Cookie、代理、證書、多部分表單等高級功能,性能優於 file_get_contents。
$host = 'target.com';
$path = '/page.php';
$referer = 'https://fake-source.com/referrer-page';
$port = 80;
$fp = fsockopen($host, $port, $errno, $errstr, 10);
if (!$fp) {
throw new Exception("連接失敗: $errstr ($errno)");
}
// 構造原始 HTTP 請求
$out = "GET $path HTTP/1.1\r\n";
$out .= "Host: $host\r\n";
$out .= "Referer: $referer\r\n";
$out .= "User-Agent: Mozilla/5.0\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
$response = '';
while (!feof($fp)) {
$response .= fgets($fp, 1024);
}
fclose($fp);
// 分離頭部和體
list($headers, $body) = explode("\r\n\r\n", $response, 2);
echo "響應頭:\n$headers\n\n響應體:\n$body";
特點:完全手動控制每個字節,可實現特殊協議細節,但需自行處理分塊傳輸、gzip 解壓、HTTPS (需 SSL 上下文) 等複雜情況。
| 維度 | file_get_contents | cURL | fsockopen |
|---|---|---|---|
| 代碼複雜度 | 低 | 中 | 高 |
| 功能豐富度 | 基礎 | 最全 | 完全可控 |
| 性能 | 中 | 高 | 高 |
| HTTPS 支援 | 需配置 | 原生 | 需 SSL 上下文 |
| 推薦場景 | 簡單 GET | 通用生產環境 | 特殊協議研究 |
$_SERVER['REMOTE_ADDR'] 白名單Set-Cookie: ...; SameSite=Strict 防 CSRFReferrer-Policy: strict-origin-when-cross-origin 控制瀏覽器發送策略技術本無善惡,關鍵在於使用場景與目的。掌握偽造手法是為了更好地防禦,請在合法授權範圍內使用。