Land your first dev job — 100% money-back guarantee.
Continue

Streams & Buffers in PHP

Learn to work with PHP streams for reading and writing files, network sockets, and memory buffers using stream wrappers and filters.

What Are Streams?

A stream is a generalised I/O interface in PHP. Instead of loading an entire file or network response into memory, you work with a flow of data that can be read or written incrementally. PHP's stream layer unifies files, network sockets, compressed archives, and in-memory buffers behind a single API.

1. Why Streams Exist

Process data without loading it all into memory at once.

2. Stream Types in PHP

Files, network, memory, compression — all use the same API.

Reading Streams

PHP provides several functions for reading from stream resources — by character, by line, by chunk, or all at once.

1. fread() and fgets()

Read by chunk or by line.

2. stream_get_contents()

Read remaining stream content into a string.

3. Reading Large Files in Chunks

Process multi-GB files with constant memory.

Writing Streams

Writing to a stream is symmetric with reading. PHP uses `fwrite()` for all stream types.

1. fwrite()

Write bytes to any stream resource.

2. In-Memory Stream (php://memory)

Build content in memory without touching the filesystem.

3. Output Buffering (ob_start / ob_get_clean)

Capture echo/print output into a string buffer.

Copying & Piping Streams

PHP provides `stream_copy_to_stream()` to pipe data directly between any two streams — the PHP equivalent of Unix pipes or Node.js `.pipe()`.

1. stream_copy_to_stream()

Pipe data from one stream to another.

2. Buffered Writes with stream_set_write_buffer()

Control how aggressively PHP flushes write buffers.

Stream Wrappers

Stream wrappers let you use a URL-style protocol prefix (`file://`, `http://`, `compress.zlib://`, `data://`) with any stream function. PHP ships with several built-in wrappers.

1. Built-in Stream Wrappers

file://, http://, php://, compress.zlib://, data://

2. Stream Context Options

Configure HTTP method, headers, and timeouts for network streams.

Stream Filters

Stream filters process data in transit — applying encoding, compression, or custom transformations without loading everything into memory.

1. Built-in Filters

string.toupper, string.rot13, convert.base64-encode, zlib.deflate, etc.

2. Custom Stream Filter

Extend php_user_filter to build your own transform.

Best Practices

Streams require careful resource management. Always close handles, handle errors, and prefer streaming over full-load for data over a few MB.

1. Always Close Stream Handles

Use try/finally to guarantee fclose() runs.

2. When to Use Streams vs file_get_contents()

Choose the right tool based on data size.