HTTP context 选项
HTTP context 选项 — HTTP context 的选项列表
说明
提供给 http://
和 https://
传输协议的 context 选项。
transports.
范例
示例 #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 忽略重定向并获取 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 的元数据一样
var_dump(stream_get_meta_data($stream));
// $url 的实际数据
var_dump(stream_get_contents($stream));
fclose($stream);
?>
注释
注意: 底层 socket stream 上下文选项
Additional context options may be supported by the underlying transport Forhttp://
streams, refer to context options for thetcp://
transport. Forhttps://
streams, refer to context options for thessl://
transport.
注意: HTTP 状态行
When this stream wrapper follows a redirect, thewrapper_data
returned by stream_get_meta_data() might not necessarily contain the HTTP status line that actually applies to the content data at index0
.第一个请求返回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
)。

User Contributed Notes 10 notes
nate ¶
8 years ago
Note that if you set the protocol_version option to 1.1 and the server you are requesting from is configured to use keep-alive connections, the function (fopen, file_get_contents, etc.) will "be slow" and take a long time to complete. This is a feature of the HTTP 1.1 protocol you are unlikely to use with stream contexts in PHP.
Simply add a "Connection: close" header to the request to eliminate the keep-alive timeout:
<?php
// php 5.4 : array syntax and header option with array value
$data = file_get_contents('http://www.example.com/', null, stream_context_create([
'http' => [
'protocol_version' => 1.1,
'header' => [
'Connection: close',
],
],
]));
?>
daniel.peder (a) gmail.com ¶
4 years ago
note that both http and https transports require the same context name http
// OK example:
// this will work as expected
// note the url with https but context with http
$correct_data = file_get_contents('https://example.com', false, stream_context_create(array('http' => array(...))));
// INVALID example:
// this will not work, the context will be ignored
// note the url with https also context with https
$correct_data = file_get_contents('https://example.com', false, stream_context_create(array('https' => array(...))));
daniel dot peder at gmail dot com ¶
4 years ago
note that for both http and https protocols require the same 'http' context keyword:
<?php
// CORRECT example:
// this will work as expected
// note the url with https but context with http
$correct_data = file_get_contents('https://example.com', false, stream_context_create(array('http' => array(...))));
// INVALID example:
// this will not work, the context will be ignored
// note the url with https also context with https
$correct_data = file_get_contents('https://example.com', false, stream_context_create(array('https' => array(...))));
gourav sarkar ¶
11 years ago
watch your case when using methods (POST and GET)...it must be always uppercase. in case of you write it in lower case it wont work.
ywarnier at beeznest dot org ¶
4 years ago
Note that setting request_fulluri to true will *change* the value of $_SERVER['REQUEST_URI] on the receiving end (from /abc.php to http://domain.com/abc.php).
aruntechguy at outlook dot com ¶
4 years ago
If you want to use Basic Auth while using get_headers(), use stream_context options below.
I am using HEAD method here, but please feel free to use GET also.
<?php
$targetUrl = 'http or https target url here';
$basicAuth = base64_encode('username:password');
stream_context_set_default(
[
'http' => [
'method' => 'HEAD',
'header' => 'Authorization: Basic ' . $basicAuth
]
]
);
$result = get_headers($targetUrl);
print_r($result);
vchampion at gmail dot com ¶
9 years ago
If you use the proxy server and encounter an error "fopen(http://example.com): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request" note that in many situations you need also set the parameter "request_fulluri" to "true" in your stream options. Without this option the php script sends the empty request to the server as "GET / HTTP/0.0" and the proxy server replies to it with the "HTTP 400" error.
For example (working sample):
<?php
$stream = stream_context_create(Array("http" => Array("method" => "GET",
"timeout" => 20,
"header" => "User-agent: Myagent",
"proxy" => "tcp://my-proxy.localnet:3128",
'request_fulluri' => True /* without this option we get an HTTP error! */
)));
if ( $fp = fopen("http://example.com", 'r', false, $stream) ) {
print "well done";
}
?>
P>S> PHP 5.3.17
jay ¶
7 years ago
Remember to match content with Content-type:
<?php
$data = array(
'var1' => 'some content',
'var2' => 'doh'
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/json', // here...
'content' => json_encode($data) // and here.
)
);
. . .
?>
chris ¶
8 years ago
I had quite a bit of trouble trying to make a request with fopen through a proxy to a secure url. I kept getting a 400 Bad Request back from the remote host. It was receiving the proxy url as the SNI host. In order to get around this I had to explicity set the SNI host to the domain I was trying to reach. It's apparently the issue outlined in this bug:
https://bugs.php.net/bug.php?id=63519
<?php
$domain = parse_url($file, PHP_URL_HOST);
$proxy_string = "tcp://" . WP_PROXY_HOST . ":" . WP_PROXY_PORT;
$opts = array(
'http' => array( 'proxy' => $proxy_string ),
'ssl' => array( 'SNI_enabled' => true, 'SNI_server_name' => $domain));
$context = stream_context_create($opts);
$handle = fopen( $file, 'r', false, $context );
?>
ASchmidt at Anamera dot net ¶
1 year ago
With the default of
'follow_location' => 1
be certain NEVER include a "Host:" header in the 'header' array.
If the host is set to "mydomain.com", and that web site has a (quite common) redirect to "www.mydomain.com", then the initial request to "http://mydomain.com" will get the expected response of:
HTTP/1.1 301 Moved Permanently
Location: http://www.mydomain.com/
However, the follow-up request does NOT replace the original "host" header with the new "location" value, as one would expect. Consequently each "follow-location" request will again be served by the original host of "http://mydomain.com", and continue the redirect loop until 'max_redirects' has been exhausted.
(For details: https://bugs.php.net/bug.php?id=77889)