Php http stream context

stream_context_create

Creates and returns a stream context with any options supplied in options preset.

Parameters

Must be an associative array of associative arrays in the format $arr[‘wrapper’][‘option’] = $value , or null . Refer to context options for a list of available wrappers and options.

Defaults to null .

Must be an associative array in the format $arr[‘parameter’] = $value , or null . Refer to context parameters for a listing of standard stream parameters.

Return Values

A stream context resource .

Changelog

Examples

Example #1 Using stream_context_create()

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

See Also

  • stream_context_set_option() — Sets an option for a stream/wrapper/context
  • Listing of supported wrappers (Supported Protocols and Wrappers)
  • Context options (Context options and parameters)

User Contributed Notes 15 notes

Something to keep in mind when creating SSL streams (using https://):

$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:

$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:

$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:

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

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,

$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:

$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.

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

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:
$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.
$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.

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

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.

$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

In some cases, set a header option as an array, and not a string, depending on server configuration.

$opts = array(
‘http’ => array(
‘method’ => «GET» ,
‘header’ => array( «Cookie: foo default»>bar «l ),
‘user_agent’=> $_SERVER [ ‘HTTP_USER_AGENT’]
)
);
?>

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.

$fileHandle = fopen(«someImage.jpg», «rb»);
$fileContents = stream_get_contents($fileHandle);
fclose($fileHandle);

Источник

Функции для работы с потоками

I can’t find any real documentation on the quoted-printable-encode stream filter, but I’ve gathered info from several places. It seems there are 4 options that can be passed in the param array as in my other note on this subject:

line-length: integer, simply sets line length before a soft break is inserted
line-break-chars: Which char or chars to consider as a line break — note that «\r\n» will only match CRLF, not CR or LF, so make sure it matches your content.
binary: boolean, hex encodes all control chars, including spaces and line breaks, but leaves alphanumerics untouched
force-encode-first: Forcibly hex-encodes the first char on each line, even if it’s alphanumeric. This is useful for avoiding corruption in some incompetent mail servers, like Exchange.

As this article says, there is no quoted_printable_encode function() in PHP: http://www.zend.com/manual/filters.convert.php

However there is a stream filter for quoted printable encoding. Here’s an example function that produces output suitable for email and doesn’t explicitly use external files (though it might do for strings over 2Mb due to the nature of the temp stream type):

function quoted_printable_encode ( $string ) $fp = fopen ( ‘php://temp/’ , ‘r+’ );
$params = array( ‘line-length’ => 70 , ‘line-break-chars’ => «\r\n» );
stream_filter_append ( $fp , ‘convert.quoted-printable-encode’ , STREAM_FILTER_READ , $params );
fputs ( $fp , $string );
rewind ( $fp );
return stream_get_contents ( $fp );
>

echo quoted_printable_encode ( str_repeat ( «hello there » , 50 ). » a=1\r\n» ). «\n» ;
?>

The filter needs to be restricted to STREAM_FILTER_READ because by default it will get filtered both going into and out of the stream, and will thus get encoded twice.

It should be much faster than using a PHP implementation of the same thing, though note that this will only work in PHP 5.1+.

Оцените статью