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);
$opts = ['http'=>['proxy'=>'tcp://proxy:8080','request_fulluri'=>true]];
$ctx = stream_context_create($opts);
$html = file_get_contents('https://target.com', false, $ctx);
$opts = ['http'=>['timeout'=>5,'connect_timeout'=>3]];
$ctx = stream_context_create($opts);
$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);
$opts = ['ssl'=>['verify_peer'=>false,'verify_peer_name'=>false]];
$ctx = stream_context_create($opts);
⚠️ 生產環境嚴禁關閉驗證
$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 可同時設定 http、https、ftp、ssl 等區塊,file_get_contents 依 URI scheme 自動套用對應區塊。
fopen + stream_copy_to_stream 串流,避免記憶體暴增。善用 stream_context_create,即可在不引入額外依賴的前提下,實現 80% 的 HTTP 客戶端需求。