PHP8 HTTP context 選項

2023-08-22 14:04 更新

HTTP context 選項 — HTTP context 的選項列表

說明

提供給 http:// 和 https:// 傳輸協(xié)議的 context 選項。 transports.

可選項

method string

遠程服務器支持的 GET,POST 或其它 HTTP 方法。

默認值是 GET。

header array 或 string

請求期間發(fā)送的附加 header 。此選項中的值將覆蓋其他值 (如 User-agent:, Host: 和 Authentication:), 即使在執(zhí)行 Location: 重定向時也是如此。 所以,如果啟用了 follow_location 就不建議設置 Host: header。

user_agent string

要發(fā)送的 header User-Agent: 的值。如果在上面的 header context 選項中沒有指定 user-agent,此值將被使用。

默認使用 php.ini 中設置的 user_agent。

content string

在 header 后面要發(fā)送的額外數(shù)據(jù)。通常使用POST或PUT請求。

proxy string

URI 指定的代理服務器的地址。(e.g. tcp://proxy.example.com:5100).

request_fulluri bool

當設置為 true 時,在構建請求時將使用整個 URI 。(例如: GET http://www.example.com/path/to/file.html HTTP/1.0)。 雖然這是一個非標準的請求格式,但某些代理服務器需要它。

默認值是 false.

follow_location int

跟隨 Location header 的重定向。設置為 0 以禁用。

默認值是 1

max_redirects int

跟隨重定向的最大次數(shù)。值為 1 或更少則意味不跟隨重定向。

默認值是 20

protocol_version float

HTTP 協(xié)議版本。

PHP 8.0.0 起默認值是 1.1。在此之前默認值是 1.0。

timeout float

讀取超時時間,單位為秒(s),用 float 指定(e.g. 10.5)。

默認使用 php.ini 中設置的 default_socket_timeout。

ignore_errors bool

即使是故障狀態(tài)碼依然獲取內容。

默認值為 false.

示例

示例 #1 獲取一個頁面并發(fā)送 POST 數(shù)據(jù)

<?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 忽略重定向并獲取 header 和內容

<?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);

// header 信息和 stream 的元數(shù)據(jù)一樣
var_dump(stream_get_meta_data($stream));

// $url 的實際數(shù)據(jù)
var_dump(stream_get_contents($stream));
fclose($stream);
?>

注釋

注意: 底層 socket stream 上下文選項Additional context options may be supported by the underlying transport For http:// streams, refer to context options for the tcp:// transport. For https:// streams, refer to context options for the ssl:// transport.
注意: HTTP 狀態(tài)行When this stream wrapper follows a redirect, the wrapper_data returned by stream_get_meta_data() might not necessarily contain the HTTP status line that actually applies to the content data at index 0.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 (永久重定向), 因此 stream 包裝器自動跟隨重定向到獲得 200 響應(index = 4)。

參見

  • http://
  • 套接字上下文選項
  • SSL 上下文選項


以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號