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

PHP stream_context_create 實戰:HTTP 請求上下文配置全攻略

     編輯:PHP 綜合知識

stream_context_create() 建立流上下文,注入參數至 file_get_contents、fopen、readfile 等函式,實現 timeout、proxy、header、method、SSL 等精細控制。

核心參數結構

<?php
$opts = [
    'http' => [
        'method'        => 'POST',           // GET/POST/PUT/DELETE...
        'header'        => "Content-Type: application/json\r\nAuth: Bearer xxx",
        'content'       => json_encode(['key' => 'value']), // POST body
        'timeout'       => 10,               // 秒,總超時
        'connect_timeout' => 5,             // 秒,連線超時(PHP 7.1+)
        'proxy'         => 'tcp://1.2.3.4:8080',
        'request_fulluri' => true,          // 代理需完整 URI
        'follow_location' => 1,             // 跟隨 3xx 重導向
        'max_redirects'   => 10,
        'ignore_errors'   => false,         // 4xx/5xx 不拋錯,回傳內容
    ],
    'ssl' => [
        'verify_peer'      => true,
        'verify_peer_name' => true,
        'cafile'           => '/etc/ssl/certs/ca-certificates.crt',
        'ciphers'          => 'HIGH:!aNULL:!MD5',
    ],
];
$ctx = stream_context_create($opts);

常見實戰場景

1. 設定代理(爬蟲/內網穿透)
$opts = ['http'=>['proxy'=>'tcp://proxy:8080','request_fulluri'=>true]];
$ctx = stream_context_create($opts);
$html = file_get_contents('https://target.com', false, $ctx);
2. 控制超時(防止阻塞)
$opts = ['http'=>['timeout'=>5,'connect_timeout'=>3]];
$ctx = stream_context_create($opts);
3. 發送 JSON POST(API 串接)
$data = json_encode(['order_id'=>123]);
$opts = ['http'=>[
    'method'=>'POST',
    'header'=>"Content-Type: application/json\r\nContent-Length: ".strlen($data),
    'content'=>$data,
]];
$ctx = stream_context_create($opts);
$resp = file_get_contents('https://api.example.com/order', false, $ctx);
4. 忽略 HTTPS 憑證驗證(測試環境)
$opts = ['ssl'=>['verify_peer'=>false,'verify_peer_name'=>false]];
$ctx = stream_context_create($opts);
⚠️ 生產環境嚴禁關閉驗證

取得回應 Header 與狀態碼

$ctx = stream_context_create(['http'=>['ignore_errors'=>true]]);
$body = file_get_contents($url, false, $ctx);
$headers = $http_response_header; // 內建變數,自動填入回應 Header 陣列
$statusLine = $headers[0]; // HTTP/1.1 200 OK

進階:多協議混合 Context

同一 Context 可同時設定 http、https、ftp、ssl 等區塊,file_get_contents 依 URI scheme 自動套用對應區塊。

效能提示

  • Context 建立有微小開銷,高頻呼叫可**快取重用** Context 物件。
  • 大檔案下載改用 fopen + stream_copy_to_stream 串流,避免記憶體暴增。
  • 極高併發場景建議改用 cURL 或 Swoole 協程客戶端。

善用 stream_context_create,即可在不引入額外依賴的前提下,實現 80% 的 HTTP 客戶端需求。

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