HTTP 內容選項
HTTP 內容選項 — HTTP 內容選項列表
說明
http:// 和 https:// 傳輸的內容選項。
選項
-
method 字串
-
GET、POST 或遠端伺服器支援的任何其他 HTTP 方法。
預設為 GET。
-
請求期間要發送的額外標頭。此選項中的值會覆蓋其他值(例如 User-agent:、Host: 和 Authentication:),即使在跟隨 Location: 重定向時也是如此。因此,如果啟用了 follow_location,則不建議設定 Host: 標頭。
-
user_agent 字串
-
要與 User-Agent: 標頭一起發送的值。僅當在上面的 header 上下文選項中*未*指定使用者代理時,才會使用此值。
預設情況下,會使用 user_agent php.ini 設定。
-
content 字串
-
在標頭之後要發送的額外資料。通常與 POST 或 PUT 請求一起使用。
-
proxy 字串
-
指定代理伺服器位址的 URI(例如 tcp://proxy.example.com:5100)。
-
request_fulluri 布林值
-
設定為 true 時,建構請求時將使用整個 URI(例如 GET http://www.example.com/path/to/file.html HTTP/1.0)。雖然這是非標準的請求格式,但某些代理伺服器需要它。
預設為 false。
-
follow_location 整數
-
跟隨 Location 標頭重定向。設定為 0 可停用。
預設為 1。
-
max_redirects 整數
-
要跟隨的最大重定向次數。值 1 或更小表示不跟隨任何重定向。
預設為 20。
-
protocol_version 浮點數
-
HTTP 協定版本。
從 PHP 8.0.0 開始,預設值為 1.1;在該版本之前,預設值為 1.0。
-
timeout 浮點數
-
讀取逾時(秒),以 浮點數 指定(例如 10.5)。
預設情況下,會使用 default_socket_timeout php.ini 設定。
-
ignore_errors 布林值
-
即使在失敗狀態碼時也擷取內容。
預設為 false。
範例
範例 #1 擷取頁面並傳送 POST 資料
<?php
$postdata = http_build_query(
array(
'var1' => 'some content',
'var2' => 'doh'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://example.com/submit.php', false, $context);
?>
範例 #2 忽略重新導向,但擷取標頭和內容
<?php
$url = "http://www.example.org/header.php";
$opts = array('http' =>
array(
'method' => 'GET',
'max_redirects' => '0',
'ignore_errors' => '1'
)
);
$context = stream_context_create($opts);
$stream = fopen($url, 'r', false, $context);
// 標頭資訊以及串流的詮釋資料
var_dump(stream_get_meta_data($stream));
// $url 中的實際資料
var_dump(stream_get_contents($stream));
fclose($stream);
?>
注意事項
注意:底層通訊端串流環境選項
底層傳輸方式 underlying transport 可能支援額外的上下文選項。對於 http:// 串流,請參考 tcp:// 傳輸方式的上下文選項。對於 https:// 串流,請參考 ssl:// 傳輸方式的上下文選項。
注意:HTTP 狀態行
當此串流包裝器遵循重新導向時,由 stream_get_meta_data() 返回的 wrapper_data 可能不一定包含實際應用於索引 0 處內容資料的 HTTP 狀態行。
array (
'wrapper_data' =>
array (
0 => 'HTTP/1.0 301 Moved Permanently',
1 => 'Cache-Control: no-cache',
2 => 'Connection: close',
3 => 'Location: http://example.com/foo.jpg',
4 => 'HTTP/1.1 200 OK',
...
第一個請求返回 301(永久重新導向),因此串流包裝器自動遵循重新導向以獲得 200 回應(索引 = 4)。