Lab 08: Streams & Context

Time: 40 minutes | Level: Advanced | Docker: docker run -it --rm php:8.3-cli bash

PHP's stream abstraction unifies file I/O, HTTP, memory buffers, and custom sources under a single API. Stream contexts configure transport parameters; stream filters transform data in flight.


Step 1: Built-in Stream Wrappers

<?php
// php://memory — RAM buffer, never touches disk
$mem = fopen('php://memory', 'r+');
fwrite($mem, 'Hello World from PHP streams!');
rewind($mem);
echo stream_get_contents($mem) . "\n";
fclose($mem);

// php://temp — RAM up to 2MB, then spills to disk
$tmp = fopen('php://temp', 'r+');
fwrite($tmp, 'Temporary data: ' . str_repeat('X', 100));
rewind($tmp);
echo 'Temp size: ' . strlen(stream_get_contents($tmp)) . " bytes\n";
fclose($tmp);

// php://input (read-only) / php://output (write-only) — used in web context
// php://stdin, php://stdout, php://stderr

// data:// wrapper — inline data URI
$inline = fopen('data://text/plain,Hello%20Inline!', 'r');
echo stream_get_contents($inline) . "\n";
fclose($inline);

📸 Verified Output:


Step 2: Stream Contexts for HTTP

📸 Verified Output:


Step 3: Reading URLs with file_get_contents

📸 Verified Output:


Step 4: Stream Filters

📸 Verified Output:


Step 5: Zlib Compression Filter

📸 Verified Output:

💡 zlib.deflate produces raw deflate data (no zlib header). Use zlib.compress/zlib.uncompress for zlib-framed data.


Step 6: Custom Stream Filter

📸 Verified Output:


Step 7: Custom Stream Wrapper

📸 Verified Output:


Step 8: Capstone — Streaming ETL Pipeline with Filters

📸 Verified Output:


Summary

Feature
Function/Class
Use Case

Memory buffer

fopen('php://memory', 'r+')

In-memory I/O

HTTP context

stream_context_create(['http' => ...])

Configure HTTP requests

SSL context

['ssl' => ['verify_peer' => true]]

TLS configuration

Apply filter

stream_filter_append($fp, 'name')

Transform data in-flight

String filters

string.toupper, string.rot13

Text transformation

Compression

zlib.deflate / zlib.inflate

Streaming compression

Custom filter

class Foo extends php_user_filter

Custom transformations

Custom wrapper

stream_wrapper_register('proto', Class)

Virtual filesystems

Read via filter

file_get_contents($url, false, $ctx)

Filtered file reading

Last updated