PHP.mk документација

stream_context_create

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.stream-context-create.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.stream-context-create.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
stream_context_create

Референца за `function.stream-context-create.php` со подобрена типографија и навигација.

function.stream-context-create.php

stream_context_create

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

stream_context_createСоздава контекст на поток

= NULL

stream_context_create(?array $options = null, ?array $params = null): resource

Создава и враќа контекст на поток со сите опции дадени во options preset.

Параметри

options

Мора да биде асоцијативен низ од асоцијативни низи во формат $arr['wrapper']['option'] = $value, или null. Погледнете опции на контекст за список на достапни обвивки и опции.

Стандардно е null.

params

Мора да биде асоцијативен низ во формат $arr['parameter'] = $value, или null. Погледнете параметри на контекст за список на стандардни параметри на поток.

Вратени вредности

Контекст на поток resource.

Дневник на промени

Верзија = NULL
8.0.0 options and params се сега null.

Примери

Пример #1 Користење stream_context_create()

<?php
$opts
= [
'http' => [
'method' => "GET",
// Use CRLF \r\n to separate multiple headers
'header' => "Accept-language: en\r\n" .
"Cookie: foo=bar",
]
];

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

Види Исто така

Белешки од корисници 11 белешки

jrubenstein на gmail точка com
пред 18 години
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);
?>
contact (на) thepointsolution.com
пред 15 години
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.
net_navard на yahoo точка com
20 години пред
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
Бен Џ
пред 13 години
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:[email protected]",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:[email protected]",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.
davep на atomicdroplet точка com
пред 18 години
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
louis.huppenbauer на gmail.com
пред 13 години
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
rlintern на gmail.com
пред 17 години
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);
Анди
пред 10 години
Don't try to re-use the ressource returned by stream_context_create. It seems not to work when connecting to different domains using https.
Брајан Готиер
пред 16 години
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']
  )
);
?>
mathieu точка laurent на gmail точка com
пред 16 години
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;

?>
sp0n9e на gmail точка com
19 години пред
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);

?>
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.