Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream context in PHP - what is it?

Tags:

php

stream

I have searched for hours and I cannot figure out what a 'stream context' in PHP is. I'm trying to use an API and it involves using this 'stream context'.

The documentation says:

A context is a set of parameters and wrapper specific options which modify or enhance the behavior of a stream.

  1. A parameter of what?
  2. What is meant by an option being 'specific to a wrapper'?
  3. What stream?

Here is the code I'm talking about:

// Encode the credentials and create the stream context.
$auth = base64_encode("$acctKey:$acctKey");
$data = array(
'http' => array(
'request_fulluri' => true,
// ignore_errors can help debug – remove for production. This option added in PHP 5.2.10
'ignore_errors' => true,
'header' => "Authorization: Basic $auth")
);
$context = stream_context_create($data);
// Get the response from Bing.
$response = file_get_contents($requestUri, 0, $context);
like image 924
user2537201 Avatar asked Jun 30 '13 20:06

user2537201


2 Answers

It took me a while to understand the stream contexts options and wrappers of PHP. I wrote an article about what helped me finally wrap my brain around how to understand PHP stream contexts options and wrappers. I hope it helps.

To properly handle whatever is coming down the line (streamed data), you will need the appropriate code to handle the different kinds of items being passed (data types). The tools for handling each different kind of data type are the “parameters”.

The “context” is determined by what is being pass along (streamed). So for different “contexts” (kinds of items) being “streamed” (passed along) the “parameters” (required tools for handling) the “data type” (kind of item) will change.

The term context simply makes reference to the fact that for different data types the situation is unique with its own required parameters.

The PHP stream wrapper would require a context in order to know which parameters are needed to handle the data type.

like image 200
LoveFineArt Avatar answered Oct 25 '22 15:10

LoveFineArt


  1. A parameter of the context that modifies the properties of the stream.

  2. The options are specific to whatever wrapper the stream is using. Examples of these include files, all the different php:// URIs, the HTTP wrapper (like when you do file_get_contents('http://example.com') — it’s not the same thing as file_get_contents('some-file.txt'))

  3. Any stream!

In this case, the stream context is passed to file_get_contents to tell it to send that authorization header and those options to the wrapper that allows file_get_contents to get contents from HTTP URLs.

You can find a list of the HTTP context options on the PHP website.

like image 39
Ry- Avatar answered Oct 25 '22 16:10

Ry-