(PHP 4 >= 4.3.0, PHP 5)
stream_context_create — Creates a stream context
$options
[, array $params
]] )
Creates and returns a stream context with any options supplied in
options
preset.
options
Must be an associative array of associative arrays in the format $arr['wrapper']['option'] = $value.
Default to an empty array.
params
Must be an associative array in the format $arr['parameter'] = $value. Refer to context parameters for a listing of standard stream parameters.
A stream context resource.
版本 | 说明 |
---|---|
5.3.0 |
Added the optional params argument.
|
Example #1 Using stream_context_create()
<?php
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
/* Sends an http request to www.example.com
with additional headers shown above */
$fp = fopen('http://www.example.com', 'r', false, $context);
fpassthru($fp);
fclose($fp);
?>
ksloan at 2dialog dot com (2013-02-21 02:28:23)
So when trying to troubleshoot a stream, I was able to var_dump and it came back as expected, but it turns out var_export does not work as intended. It always comes back as null.
Use is_resource()
<?php file_put_contents( "/tmp/debug", var_export( is_resource($stream), true ) ); ?>
to get a true/false if the stream is getting made or not.
Ben J (2013-01-08 15:28:45)
I spent a good five hours trying to figure this out, so hopefully it will save someone else some time.
When you are trying to download a file via ftp through an HTTP proxy note that the following will not be enough:
<?php
$opts = array('ftp' => array(
'proxy' => 'tcp://vbinprst10:8080',
'request_fulluri'=>true,
'header' => array(
"Proxy-Authorization: Basic $auth"
)
)
);
$context = stream_context_create($opts);
$s = file_get_contents("ftp://anonymous:anonymous@ftp.example.org",false,$context);
?>
Your proxy will respond that authentication is required. You may scratch your head and think "but I'm providing authentication!"
The issue is that the 'header' value is only applicable to http connections. So to authenticate on a proxy, you first have to pull a file from HTTP, before the context is valid for using on FTP.
<?php
$opts = array('ftp' => array(
'proxy' => 'tcp://vbinprst10:8080',
'request_fulluri'=>true,
'header' => array(
"Proxy-Authorization: Basic $auth"
)
),
'http' => array(
'proxy' => 'tcp://vbinprst10:8080',
'request_fulluri'=>true,
'header' => array(
"Proxy-Authorization: Basic $auth"
)
)
);
$context = stream_context_create($opts);
$s = file_get_contents("http://www.example.com",false,$context);
$s = file_get_contents("ftp://anonymous:anonymous@ftp.example.org",false,$context);
?>
It's a bit roundabout, but it works. Note that the 'header' val in the ftp array is redundant, but I kept it in anyway.
louis dot huppenbauer at gmail dot com (2012-09-25 06:04:32)
When using the https protocol you'll have to make sure to set the right context options to use the full "power" of the ssl/tls encryption.
<?php
$url = 'https://secure.example.com/test/1';
$contextOptions = array(
'ssl' => array(
'verify_peer' => true,
'cafile' => __DIR__ . '/cacert.pem',
'verify_depth' => 5,
'CN_match' => 'secure.example.com'
)
);
$sslContext = stream_context_create($contextOptions);
$result = file_get_contents($url, NULL, $sslContext);
?>
More information about those context options can be found at http://php.net/manual/en/context.ssl.php
Anonymous (2010-10-22 22:45:58)
If you are trying to set a custom http header on php 5.2.x, try this:
<?php
// build header and set it the usual way
$authenticationHeader = $headername . ': ' . $headervalue;
$opts = array(
'http' => array(
'header' => $authenticationHeader
)
);
// workaround for php bug where http headers don't get sent in php 5.2
if(version_compare(PHP_VERSION, '5.3.0') == -1){
ini_set('user_agent', 'PHP-SOAP/' . PHP_VERSION . "\r\n" . $authenticationHeader);
}
$context = stream_context_create($opts);
// now use context for soap call or whatever...
?>
this is the only option that worked for me.
contact (at) thepointsolution.com (2010-08-12 05:29:18)
I big NOTE that i hope will help some one. Something that is not mentioned in the documentation, is that when php is compiled --with-curlwrappers,
So, instead of:
<?php
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
?>
You would setup the header this way:
<?php
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>array("Accept-language: en",
"Cookie: foo=bar",
"Custom-Header: value")
)
);
$context = stream_context_create($opts);
?>
This will work.
mathieu dot laurent at gmail dot com (2009-07-30 06:15:03)
Connection via Proxy
<?php
$opts = array('http' => array('proxy' => 'tcp://127.0.0.1:8080', 'request_fulluri' => true));
$context = stream_context_create($opts);
$data = file_get_contents('http://www.php.net', false, $context);
echo $data;
?>
Brian Gottier (2009-05-16 12:13:29)
In some cases, set a header option as an array, and not a string, depending on server configuration.
<?php
$opts = array(
'http'=> array(
'method'=> "GET",
'header'=> array( "Cookie: foo="bar"l ),
'user_agent'=> $_SERVER['HTTP_USER_AGENT']
)
);
?>
dresel at gmx dot at (2009-04-21 02:23:06)
I use this script to send normal data and images (you may have to change Content-Type to send other data), works fine for me :)
<?php
function do_post_request($url, $postdata, $files = null)
{
$data = "";
$boundary = "---------------------".substr(md5(rand(0,32000)), 0, 10);
//Collect Postdata
foreach($postdata as $key => $val)
{
$data .= "--$boundary\n";
$data .= "Content-Disposition: form-data; name=\"".$key."\"\n\n".$val."\n";
}
$data .= "--$boundary\n";
//Collect Filedata
foreach($files as $key => $file)
{
$fileContents = file_get_contents($file['tmp_name']);
$data .= "Content-Disposition: form-data; name=\"{$key}\"; filename=\"{$file['name']}\"\n";
$data .= "Content-Type: image/jpeg\n";
$data .= "Content-Transfer-Encoding: binary\n\n";
$data .= $fileContents."\n";
$data .= "--$boundary--\n";
}
$params = array('http' => array(
'method' => 'POST',
'header' => 'Content-Type: multipart/form-data; boundary='.$boundary,
'content' => $data
));
$ctx = stream_context_create($params);
$fp = fopen($url, 'rb', false, $ctx);
if (!$fp) {
throw new Exception("Problem with $url, $php_errormsg");
}
$response = @stream_get_contents($fp);
if ($response === false) {
throw new Exception("Problem reading data from $url, $php_errormsg");
}
return $response;
}
//set data (in this example from post)
//sample data
$postdata = array(
'name' => $_POST['name'],
'age' => $_POST['age'],
'sex' => $_POST['sex']
);
//sample image
$files['image'] = $_FILES['image'];
do_post_request("http://example.com", $postdata, $files);
?>
rlintern at gmail dot com (2009-02-20 09:56:15)
I found the following code worked for me for POSTing some binary data to a remote server. I am putting it here since I could not find a quick solution to this by 'googling' or looking through this documentation.
Disclaimer: I have no idea if this a 'good' solution, since I'm new to PHP, but it may just suit your needs as it did mine. I am assuming bad things will happen with very large files since the entire file is read into $fileContents.
I am using PHP 5.2.8.
$fileHandle = fopen("someImage.jpg", "rb");
$fileContents = stream_get_contents($fileHandle);
fclose($fileHandle);
$params = array(
'http' => array
(
'method' => 'POST',
'header'=>"Content-Type: multipart/form-data\r\n",
'content' => $fileContents
)
);
$url = "http://somesite.somecompany.com?someParam=someValue";
$ctx = stream_context_create($params);
$fp = fopen($url, 'rb', false, $ctx);
$response = stream_get_contents($fp);
davep at atomicdroplet dot com (2007-05-17 16:02:10)
In addition to the context options mentioned above (appendix N), lower down context options for sockets can be found in appendix P - http://www.php.net/manual/en/transports.php
jrubenstein at gmail dot com (2007-04-27 09:36:09)
Something to keep in mind when creating SSL streams (using https://):
<?php
$context = context_create_stream($context_options)
$fp = fopen('https://url', 'r', false, $context);
?>
One would think - the proper way to create a stream options array, would be as follows:
<?php
$context_options = array (
'https' => array (
'method' => 'POST',
'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
. "Content-Length: " . strlen($data) . "\r\n",
'content' => $data
)
);
?>
THAT IS THE WRONG WAY!!!
Take notice to the 3rd line: 'https' => array (
The CORRECT way, is as follows:
<?php
$context_options = array (
'http' => array (
'method' => 'POST',
'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
. "Content-Length: " . strlen($data) . "\r\n",
'content' => $data
)
);
?>
Notice, the NEW 3rd line: 'http' => array (
Now - keep this in mind - I spent several hours trying to trouble shoot my issue, when I finally stumbled upon this non-documented issue.
The complete code to post to a secure page is as follows:
<?php
$data = array ('foo' => 'bar', 'bar' => 'baz');
$data = http_build_query($data);
$context_options = array (
'http' => array (
'method' => 'POST',
'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
. "Content-Length: " . strlen($data) . "\r\n",
'content' => $data
)
);
$context = context_create_stream($context_options)
$fp = fopen('https://url', 'r', false, $context);
?>
chris dot vigelius at gmx dot net (2007-04-11 05:34:33)
It seems that the authorization example given below by"php at charlesconsulting dot com" does NOT work with PHP 5.2.1, since the 'header' option will be simply ignored if it is not an array (but a string).
The following works:
$url = 'http://protectedstuff.com';
$auth = base64_encode('user:password');
$header = array("Authorization: Basic $auth");
$opts = array( 'http' => array ('method'=>'GET',
'header'=>$header));
$ctx = stream_context_create($opts);
file_get_contents($url,false,$ctx);
See also http://bugs.php.net/bug.php?id=41051
php at charlesconsulting dot com (2007-01-13 07:14:12)
Here's an example of retrieving a page which requests a username and password using the basic authorization scheme. This calls the w3.org web page validator for a password protected page.
//$fileurl contains page to validate
$validateurl="http://validator.w3.org/check?uri=$fileurl";
$cred = sprintf('Authorization: Basic %s',
base64_encode('username:password') );
$opts = array(
'http'=>array(
'method'=>'GET',
'header'=>$cred)
);
$ctx = stream_context_create($opts);
$validate=file_get_contents($validateurl,false,$ctx);
sp0n9e at gmail dot com (2006-12-28 22:18:24)
Here's a very simple way to do posts easily without need of cURL or writing an http request by hand using the tcp:// wrapper. I like using contexts just because of their ubiquity and the lack of an optional library such as cURL (though one of the more popular libraries).
<?php
$options = array(
'http'=>array(
'method'=>"POST",
'header'=>
"Accept-language: en\r\n".
"Content-type: application/x-www-form-urlencoded\r\n",
'content'=>http_build_query(array('foo'=>'bar'))
));
$context = stream_context_create($options);
fopen('http://www.example.com/',false,$context);
?>
dev at zayso dot org (2006-03-05 17:31:30)
Example of a stream for reading a string passed
via a context object.
<?php
/* ----------------------------------------
* Designed to read from a string
*/
class sfStreamStringRead
{
const PROTOCOL = 'stringread'; /* Underscore not allowed */
protected $dataPos = NULL;
protected $dataBuf = NULL;
protected $dataLen = NULL;
function stream_open($path, $mode, $options, &$opened_path)
{
/* Verify context has data */
$contextOptions = stream_context_get_options($this->context);
if (!isset($contextOptions[self::PROTOCOL]['data'])) {
return FALSE;
}
$this->dataBuf = $contextOptions[self::PROTOCOL]['data'];
$this->dataLen = strlen($this->dataBuf);
$this->dataPos = 0;
return TRUE;
}
function stream_read($count){
$ret = substr($this->dataBuf, $this->dataPos, $count);
$this->dataPos += strlen($ret);
return $ret;
}
function stream_eof(){
return $this->dataPos >= $this->dataLen;
}
function stream_tell(){
return $this->dataPos;
}
/* ------------------------------------------
* A few helper functions
*/
static function genURL()
{
return self::PROTOCOL . '://';
}
static function genContext($dataBuf)
{
return stream_context_create(array(
self::PROTOCOL => array(
'data' => $dataBuf,
),
));
}
static function open($dataBuf)
{
return fopen(self::genURL(),'r',FALSE,self::genContext($dataBuf));
}
}
stream_wrapper_register(
sfStreamStringRead::PROTOCOL,
'sfStreamStringRead'
);
$sp = sfStreamStringRead::open("Some String Data\n");
echo fgets($sp);
fclose($sp);
?>
net_navard at yahoo dot com (2005-12-09 22:38:29)
Hi,you can create an array of parameters(what it's called a stream context),which can be transmitted each time you read or write a stream through a socket.In the below example:
$opts =array('http'=>arra('method'=>"GET",
'header'=>"Accept-language:en\r\n"."Cookie: foo=bar\r\n");
What you're actually doing is create a set of parameters(the protocol to be used,the request method,additional http headers and a cookie) which will be used each time you open a socket connection to request www.example.com.This saves a lot of time if you want to use these parameters (called a stream context) whenever you include them when making a request to www.example.com,instead of having to specify them over and over again.
Using the previous example,say you want to create a stream context,which sends a "Content-Type" http header and utilize it when making a request to www.example.com.Take a look:
$opts = array('http'=>array('method'=>"GET",
'header'=>"Content-Type: text/xml; charset=utf-8");
$context = stream_context_create($opts);
$fp = fopen('http://www.example.com','r',false,$context);
fpassthru($fp);
fclose($fp);
Now,when you make a request to www.example.com,the above http header will be included within the socket and transmitted to the server.Best of luck for you friends,Hossein