首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

file_get_contents 代理請求失效排查:缺失 request_fulluri 參數

     編輯:PHP 相關知識

file_get_contents 代理請求失效排查:缺失 request_fulluri 參數

使用 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 to TRUE, 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 is FALSE.

大多數代理服務器要求請求行包含完整 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」時,優先檢查此參數。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved