使用 file_get_contents 通過代理訪問外部 API 時,僅設置 proxy 參數往往不夠,必須同時啟用 request_fulluri,否則請求格式不符合代理服務器要求導致失敗。
$opt = [
"http" => [
"method" => "GET",
"header" => ["param:...", "oauthsignature:..."],
"proxy" => "tcp://proxy.example.com:5100", // 僅設置 proxy
"request_fulluri" => true // 關鍵:必須為 true
]
];
$context = stream_context_create($opt);
$res = file_get_contents($url, false, $context);
PHP 文檔 HTTP context options 說明:
request_fulluri(boolean): When set toTRUE, the entire URI will be used when constructing the request. (i.e.GET https://www.example.com/path HTTP/1.0). While this is a non-standard request format, some proxy servers require it. Default isFALSE.
大多數代理服務器要求請求行包含完整 URI(GET https://host/path HTTP/1.0),而非僅路徑(GET /path HTTP/1.0)。未開啟此選項時,發送給代理的請求格式不合規,導致代理拒絕或轉發異常。
proxy 值協議頭需用 tcp:// 而非 https://(如 tcp://proxy.ip:port)。request_fulluri => true 必須與 proxy 同時設置。request_fulluri 通常無需開啟。function httpGetViaProxy($url, $proxy) {
$opts = [
'http' => [
'method' => 'GET',
'proxy' => 'tcp://' . $proxy,
'request_fulluri' => true,
'timeout' => 30,
]
];
$ctx = stream_context_create($opts);
return file_get_contents($url, false, $ctx);
}
遇到「能直連不能走代理」或「代理返回 400/502」時,優先檢查此參數。