PHP Stream Contexts Explained with File Functions

This article provides a practical overview of stream contexts in PHP and how they can be used to customize file and network stream operations. You will learn what stream contexts are, how to create them, and how to apply them to common PHP file functions to handle tasks like custom HTTP headers, POST requests, and timeout settings.

What is a Stream Context in PHP?

In PHP, a stream represents a resource that can be read from or written to, such as a local file, a network socket, or an HTTP/FTP connection. A stream context is a collection of options and parameters that modifies the behavior of these streams.

By using stream contexts, you can instruct PHP’s built-in file functions to perform advanced operations—such as sending custom headers, utilizing specific HTTP methods (like POST or PUT), or configuring SSL/TLS settings—without needing to rely on heavier libraries like cURL.

How to Create a Stream Context

Stream contexts are created using the stream_context_create() function. This function accepts an associative array of options structured by “wrapper” (such as http, ftp, ssl, or file).

Here is the basic structure:

$options = [
    'wrapper_name' => [
        'option_name' => 'value',
    ],
];

$context = stream_context_create($options);

Using Stream Contexts with File Functions

Many of PHP’s filesystem functions accept a context resource as one of their arguments. Below are common use cases demonstrating how to implement them.

1. Making an HTTP POST Request with file_get_contents

By default, file_get_contents() performs an HTTP GET request. You can use a stream context to change the method to POST and attach payload data.

$url = 'https://api.example.com/data';
$data = json_encode(['username' => 'john_doe']);

$options = [
    'http' => [
        'method'  => 'POST',
        'header'  => "Content-Type: application/json\r\n" .
                     "Accept: application/json\r\n",
        'content' => $data,
        'timeout' => 5.0, // Timeout in seconds
    ],
];

$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);

if ($result === false) {
    // Handle error
}

2. Passing Custom Headers

Some APIs require a specific User-Agent or an Authorization token. You can pass these via the header option inside the http wrapper.

$url = 'https://api.example.com/user';

$options = [
    'http' => [
        'method' => 'GET',
        'header' => "Authorization: Bearer YOUR_API_TOKEN\r\n" .
                    "User-Agent: MyPHPApp/1.0\r\n"
    ]
];

$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);

3. Using Contexts with fopen

You can also pass a stream context to fopen(). This is useful for reading large streams line-by-line while applying custom network or file settings.

$options = [
    'http' => [
        'protocol_version' => 1.1,
        'ignore_errors' => true, // Continue reading even on 4xx/5xx status codes
    ],
];

$context = stream_context_create($options);
$handle = fopen('https://example.com', 'r', false, $context);

if ($handle) {
    while (($line = fgets($handle)) !== false) {
        echo $line;
    }
    fclose($handle);
}

Supported File Functions

Stream contexts can be used with a variety of built-in PHP functions that interact with files and URLs, including:

By mastering stream contexts, you can write lightweight, efficient PHP code that interacts seamlessly with web APIs and local resources using native file-handling functions.