Intermediate LevelPHP 8+
How do PHP Stream Wrappers work and how do you register custom protocol wrappers?
❓ Interview Prompt: Explain PHP streams architecture, built-in stream wrappers (php://input, php://memory, zlib://), and stream_wrapper_register().
Streams are a unified abstraction in PHP for reading/writing streaming data (files, network sockets, compressed archives) in chunked blocks.
1. Built-in Stream Wrappers:
•
'php://input': Read-only stream to access raw HTTP POST body payloads (JSON/XML).
•
'php://memory' / 'php://temp': Temporary memory-backed read/write streams.
•
'zlib://': Reads/writes gzipped compressed archives on the fly.
2. Custom Stream Wrappers ('stream_wrapper_register()'):
Allows registering custom protocol handlers (e.g. 's3://bucket/file.txt') so standard PHP file functions ('fopen()', 'file_get_contents()') work with cloud storage or custom protocols!
Code Implementation Example
php
<?php
// Reading raw HTTP POST JSON payload stream
$rawJson = file_get_contents('php://input');
$data = json_decode($rawJson, true);
// Writing to temporary memory-backed stream
$memStream = fopen('php://memory', 'r+');
fwrite($memStream, 'Streamed data content');
rewind($memStream);
echo stream_get_contents($memStream);
fclose($memStream);💡Reading raw HTTP request body via php://input and operating on memory streams.
🎯 Interview Key Takeaway
PHP Streams provide a unified file and network I/O abstraction. Use php://input to read raw HTTP request payloads.
#Streams#php://input#Stream Wrappers#Intermediate
Back to all PHP 8+ Questions→