PHP Stream

Beginner
10 min read
Updated: Nov 2026
3 examples
streams & wrappers

Definition and Usage

PHP streams are a single way to read and write many kinds of data: local files, HTTP responses, in-memory buffers, and network sockets. A wrapper is the scheme that tells PHP how to open that resource (file://, http://, php://, and others). List them with stream_get_wrappers().

Open a memory stream with fopen('php://memory', 'r+'), write bytes, then read them back with stream_get_contents() or stream_get_line(). Inspect a handle with stream_get_meta_data(). Copy between two open streams with stream_copy_to_stream().

A context carries options for wrappers. Build one with stream_context_create() (for example HTTP method and headers), then pass it to fopen() or file_get_contents(). Attach transforms with stream_filter_append() / stream_filter_prepend(). Socket helpers such as stream_socket_client() and stream_select() sit in the same family when you need network I/O.

This page explains the ideas. The Stream Functions index lists all 47 function guides.

Why streams exist.

They let you treat files, memory, HTTP, and sockets with the same read/write tools, so beginner code can grow from php://memory demos to real network work without learning a new API each time.

Contexts are not filters.

A context sets how a wrapper opens a resource (timeouts, HTTP headers). A filter changes the bytes as they pass through an already-open stream. Learn both: stream_context_create() and stream_filter_append().

PHP Syntax

The usual pattern: open a stream, optionally attach a context or filter, then read or write:

PHP
// Memory stream (no disk, offline-safe)
$fp = fopen('php://memory', 'r+');
fwrite($fp, "hello stream\n");
rewind($fp);
$text = stream_get_contents($fp);           // string|false
$meta = stream_get_meta_data($fp);          // array
fclose($fp);

// Context for HTTP-style options (pass to fopen / file_get_contents)
$ctx = stream_context_create([
  'http' => [
    'method'  => 'GET',
    'header'  => "Accept: text/plain\r\n",
    'timeout' => 5,
  ],
]);
$opts = stream_context_get_options($ctx);   // array

// Filter on a memory stream
$fp = fopen('php://memory', 'r+');
stream_filter_append($fp, 'string.toupper');
fwrite($fp, 'abc');
rewind($fp);
$upper = stream_get_contents($fp);          // ABC
fclose($fp);

// Inspect wrappers / filters available
$wrappers = stream_get_wrappers();          // array
$filters  = stream_get_filters();           // array

// Sockets (overview — see function guides for full use)
// $client = stream_socket_client('tcp://127.0.0.1:80');
// stream_set_blocking($client, false);
// stream_select($read, $write, $except, 0, 200000);

Core Ideas

What to remember when you work with PHP streams:

IdeaFunctionRemember
Read allstream_get_contents()Reads remaining bytes from the current position into a string; optional max length and offset
Read a linestream_get_line()Reads until a delimiter (or max length); useful for line-oriented protocols
Inspect handlestream_get_meta_data()Returns wrapper type, mode, seekability, timed_out, and more
Create contextstream_context_create()Builds an options bag (for example http method/headers) for fopen-family calls
Context optionsstream_context_get_options()Reads back options; set with stream_context_set_option() / stream_context_set_options()
Attach filterstream_filter_append()Transforms data as it flows; list names with stream_get_filters()
Wrappers liststream_get_wrappers()Shows registered schemes; register/restore with the stream_wrapper_* helpers
Blocking / selectstream_set_blocking() / stream_select()Control whether reads wait, and wait on multiple streams with a timeout
Socketsstream_socket_client()Open a client socket; pair with accept/server/send/recv helpers for TCP/UDP work
Bucketsstream_bucket_append()Low-level filter plumbing; beginners usually start with built-in filters first

Contexts, filters, and sockets

Pass a context as the last argument to fopen(), file_get_contents(), and similar calls. Filters stack on an open stream and can be removed with stream_filter_remove(). For network work, open a client with stream_socket_client(), optionally set a timeout with stream_set-timeout(), and use stream_select() when you wait on more than one socket. Custom filter authors work with buckets via stream_bucket_new() and friends.

Function Groups at a Glance

The Stream section is one family with seven jobs. Use this map to pick the right group before you open a function page:

GroupTypical jobStart here
BucketsLow-level chunks used inside custom stream filtersstream_bucket_append(), stream_bucket_new()
ContextsBuild and inspect options for wrappers (HTTP headers, timeouts)stream_context_create()
FiltersAttach, list, register, or remove byte transformsstream_filter_append()
Read & inspectRead contents, copy streams, check metadata and wrappersstream_get_contents(), stream_get_meta_data()
Blocking / buffers / selectNon-blocking mode, read/write buffers, multi-stream waitstream_set_blocking(), stream_select()
SocketsClient/server sockets, crypto, send/recv helpersstream_socket_client()
Wrappers & miscRegister wrappers, resolve include paths, notificationsstream_get_wrappers(), stream_wrapper_register()

Neighboring tutorials that often sit next to this work: Output Control for catching echoed text before it reaches a stream, Filesystem for fopen() and file helpers, Strings for editing bytes you read from a stream, and Variables for storing context arrays and captured text.

PHP Examples

Three short, offline-safe scripts: a memory stream with stream_get_contents(), an HTTP-style context you can inspect without a network call, and a string.toupper filter. Each block includes a fixed View Output panel.

Example 1 — php://memory and stream_get_contents()

Open an in-memory stream, write two lines, rewind, then read everything with stream_get_contents().

PHP
<?php
$fp = fopen('php://memory', 'r+');
fwrite($fp, 'line one' . PHP_EOL);
fwrite($fp, 'line two' . PHP_EOL);
rewind($fp);

$meta = stream_get_meta_data($fp);
$text = stream_get_contents($fp);
fclose($fp);

echo 'wrapper: ', $meta['wrapper_type'], PHP_EOL;
echo 'seekable: ', $meta['seekable'] ? 'yes' : 'no', PHP_EOL;
echo 'captured:', PHP_EOL;
echo $text;
?>

How It Works

  1. fopen('php://memory', 'r+') opens a temporary buffer in RAM—no file on disk.
  2. fwrite() stores the two lines; the write position moves to the end.
  3. rewind() moves the read pointer back to the start so the next read sees the whole buffer.
  4. stream_get_meta_data() reports wrapper type and seekability; stream_get_contents() returns the text.
  5. This is the beginner pattern for practicing streams without network or filesystem side effects.

Example 2 — HTTP context options (offline)

Build a context with HTTP method and Accept header, then print the options back—no remote request.

PHP
<?php
$ctx = stream_context_create([
  'http' => [
    'method'  => 'GET',
    'header'  => "Accept: text/plain\r\n",
    'timeout' => 5,
  ],
]);

$opts = stream_context_get_options($ctx);
echo 'method: ', $opts['http']['method'], PHP_EOL;
echo 'timeout: ', $opts['http']['timeout'], PHP_EOL;
echo 'header: ', trim($opts['http']['header']), PHP_EOL;

$wrappers = stream_get_wrappers();
echo 'has http: ', in_array('http', $wrappers, true) ? 'yes' : 'no', PHP_EOL;
?>

How It Works

  1. stream_context_create() builds an options array keyed by wrapper name (http here).
  2. Those options would be passed as the last argument to fopen() or file_get_contents() for a real request.
  3. stream_context_get_options() reads the same bag back so you can verify method, timeout, and headers.
  4. stream_get_wrappers() confirms the http scheme is registered on this install.
  5. Keeping the demo offline avoids network flakiness while you learn the context API.

Example 3 — Attach a string.toupper filter

Append the built-in string.toupper filter to a memory stream and read the transformed bytes.

PHP
<?php
$fp = fopen('php://memory', 'r+');
$filter = stream_filter_append($fp, 'string.toupper');

fwrite($fp, 'hello filters');
rewind($fp);
$out = stream_get_contents($fp);

stream_filter_remove($filter);
fclose($fp);

echo 'filtered: ', $out, PHP_EOL;
$names = stream_get_filters();
echo 'has string.toupper: ', in_array('string.toupper', $names, true) ? 'yes' : 'no', PHP_EOL;
?>

How It Works

  1. stream_filter_append() attaches string.toupper so writes (or reads, depending on filter mode) are transformed.
  2. We write lowercase text, rewind, then stream_get_contents() returns the uppercase result.
  3. stream_filter_remove() detaches the filter resource when you no longer need it.
  4. stream_get_filters() lists built-in and registered filter names on this PHP build.
  5. Custom filters use bucket helpers; start with built-in filters before writing your own.

Next: PHP Stream Functions Index

After you know what wrappers are, how php://memory works, how contexts carry HTTP options, how filters transform bytes, and how sockets fit in, open the functions index for all 47 guides.

Start withWhy
stream_bucket_append()First sidebar guide; filter bucket plumbing
stream_get_contents()Read remaining stream bytes into a string
stream_context_create()Build HTTP and other wrapper options
stream_filter_append()Attach a transform such as string.toupper
stream_get_meta_data()Inspect wrapper type, mode, and seekability
stream_set_blocking()Control whether reads wait for data
stream_socket_client()Open a client socket for TCP/UDP work

Full list: PHP Stream Functions index (/php/stream/function).

Frequently Asked Questions

A stream is a flow of data you can read from or write to with the same helpers used for files. Files, HTTP responses, memory buffers (php://memory), and sockets can all appear as streams. Wrappers give each kind of resource a scheme name such as file://, http://, or php://.
A wrapper teaches PHP how to open a particular kind of resource. Built-in wrappers include file, http, https, ftp, php, data, and more. stream_get_wrappers() lists the ones available on your install. You can also register a custom wrapper with stream_wrapper_register().
php://memory is an in-memory stream you open with fopen(). You can fwrite() into it, rewind(), then read with fread() or stream_get_contents() without touching the disk. It is ideal for offline demos and for building temporary binary or text payloads.
A context is an options bag you pass to fopen(), file_get_contents(), and similar calls. Create one with stream_context_create(). For HTTP you can set method, header, timeout, and other http wrapper options without changing how you read the response.
Filters transform data as it flows through a stream. Attach one with stream_filter_append() or stream_filter_prepend(). Built-in filters include string.toupper, string.tolower, and convert.* helpers. Custom filters use buckets (stream_bucket_*) under the hood.
Start with stream_get_contents() on a php://memory handle so you can read a whole stream into a string. Then learn stream_context_create() for HTTP options, stream_filter_append() for transforms, and stream_get_meta_data() to inspect a handle. Open the functions index for all 47 guides.

Browse every Stream function

Open the functions index for categorized guides with examples and FAQs.

Stream Functions Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful