萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP stream_context_create() 建立內容流上下文完整教學

函式用途

stream_context_create() 建立流上下文選項,供 fopen()、file_get_contents()、stream_socket_client() 等函式使用,可設定 HTTP 方法、標頭、超時、代理、SSL 驗證等。

常見選項陣列結構

$opts = [
    'http' => [
        'method'         => 'GET',           // 請求方法
        'header'         => "User-Agent: MyBot\r\nAccept: */*\r\n",
        'timeout'        => 60,              // 秒
        'proxy'          => 'tcp://127.0.0.1:8080',
        'request_fulluri'=> true,            // 使用代理時需為 true
        'follow_location'=> 1,               // 跟隨重導向
        'max_redirects'  => 10,
        'ignore_errors'  => false,
    ],
    'ssl' => [
        'verify_peer'   => false,
        'verify_peer_name' => false,
    ]
];
$context = stream_context_create($opts);

實戰範例

1. 設定代理伺服器

$opts = ['http' => ['request_fulluri' => true]];
$context = stream_context_create($opts);
$content = file_get_contents($url, false, $context);

2. 設定 HTTP 超時與方法

$opts = [
    'http' => [
        'method'  => 'GET',
        'timeout' => 60,
    ]
];
$context = stream_context_create($opts);
$html = file_get_contents('https://www.example.com', false, $context);

3. 發送 POST 請求並攜帶自訂標頭

$postData = http_build_query(['key' => 'value']);
$opts = [
    'http' => [
        'method'  => 'POST',
        'header'  => "Content-Type: application/x-www-form-urlencoded\r\nContent-Length: " . strlen($postData),
        'content' => $postData,
        'timeout' => 30,
    ]
];
$context = stream_context_create($opts);
$result = file_get_contents('https://api.example.com/endpoint', false, $context);

其他支援的封裝協定選項

  • ftp:overwrite、resume_pos、proxy
  • ssl/tls:verify_peer、cafile、local_cert、passphrase
  • zlib:壓縮層級

最佳實務

  • 預設超時 60 秒,依業務調整(API 建議 5-10 秒)。
  • 生產環境務必驗證 SSL 憑證(verify_peer = true)。
  • 重複請求同一主機時,重複使用 $context 物件。
copyright © 萬盛學電腦網 all rights reserved