PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

stream_context_get_default> <stream_bucket_prepend
Last updated: Fri, 04 Jul 2008

view this page in

stream_context_create

(PHP 4 >= 4.3.0, PHP 5)

stream_context_create — Crear un contexto de secuencia

Descripción

resource stream_context_create ([ array $opciones [, array $params ]] )

Crea y devuelve un contexto de secuencia con cualquier número de opciones dadas en el conjunto opciones .

Las opciones deben venir en una matriz asociativa de matrices asociativas en el formato $matriz['envoltura']['opcion'] = $valor. Su valor predeterminado es una matriz vacía.

params debe ser una matriz asociativa de la forma $matriz['parametro'] = $valor. Refiérase a stream_context_set_params() para un listado de parámetros de secuencia estándar.

Note: El argumento params fue agregado a PHP 6.0.0.

Example #1 Uso de stream_context_create()

<?php
$opciones 
= array(
  
'http'=>array(
    
'method'=>"GET",
    
'header'=>"Accept-language: en\r\n" .
              
"Cookie: foo=bar\r\n"
  
)
);

$contexto stream_context_create($opciones);

/* Envía una petición http a www.example.com con las cabeceras
 * adicionales mostradas anteriormente */
$da fopen('http://www.example.com''r'false$contexto);
fpassthru($da);
fclose($da);
?>

Vea también stream_context_set_option(), y el listado de envolturas soportadas con opciones de contexto (Lista de Protocolos/Envolturas Soportadas).



stream_context_get_default> <stream_bucket_prepend
Last updated: Fri, 04 Jul 2008
 
add a note add a note User Contributed Notes
stream_context_create
davep at atomicdroplet dot com
18-May-2007 01:02
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
27-Apr-2007 06:36
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
11-Apr-2007 02:34
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
13-Jan-2007 04:14
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
29-Dec-2006 07:18
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
06-Mar-2006 02:31
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
10-Dec-2005 07:38
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

stream_context_get_default> <stream_bucket_prepend
Last updated: Fri, 04 Jul 2008
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites