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);
$opts = ['http' => ['request_fulluri' => true]];
$context = stream_context_create($opts);
$content = file_get_contents($url, false, $context);
$opts = [
'http' => [
'method' => 'GET',
'timeout' => 60,
]
];
$context = stream_context_create($opts);
$html = file_get_contents('https://www.example.com', false, $context);
$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、proxyssl/tls:verify_peer、cafile、local_cert、passphrasezlib:壓縮層級verify_peer = true)。$context 物件。