Lesson 4 of 6
PHP Streams - Stream Wrappers & Context
PHP streams are a unified I/O abstraction - file, HTTP, FTP, and memory all use the same stream functions. Stream contexts let you configure HTTP headers, authentication, and SSL options for URL-based operations. Understanding streams is essential for building HTTP clients, custom file processors, and memory-efficient data pipelines.
Streams, Wrappers & HTTP with stream_context
<?php
declare(strict_types=1);
// ── Built-in stream wrappers ──────────────────────────────────
// file:// local filesystem (default for file paths)
// http:// HTTP requests via file_get_contents
// https:// HTTPS requests
// ftp:// FTP server files
// php:// PHP I/O (php://input, php://output, php://memory, php://temp)
// data:// data URIs
// compress.zlib:// gzip compressed streams
// compress.bzip2:// bzip2 compressed streams
// ── Reading HTTP with context ─────────────────────────────────
$context = stream_context_create([
"http" => [
"method" => "GET",
"header" => [
"Accept: application/json",
"User-Agent: PriygopBot/1.0",
"Authorization: Bearer " . ($_ENV["API_TOKEN"] ?? ""),
],
"timeout" => 10,
"ignore_errors" => true, // don't throw on 4xx/5xx
],
"ssl" => [
"verify_peer" => true,
"verify_peer_name" => true,
],
]);
$raw = file_get_contents("https://api.example.com/posts", context: $context);
$code = (int) explode(" ", $http_response_header[0])[1];
if ($raw === false || $code >= 400) {
throw new RuntimeException("API call failed with HTTP $code");
}
$posts = json_decode($raw, associative: true, flags: JSON_THROW_ON_ERROR);
// ── POST request via stream context ──────────────────────────
$payload = json_encode(["title" => "New Post", "body" => "Content..."]);
$context = stream_context_create([
"http" => [
"method" => "POST",
"header" => ["Content-Type: application/json", "Content-Length: " . strlen($payload)],
"content" => $payload,
],
]);
$response = file_get_contents("https://api.example.com/posts", context: $context);
// ── php://input - read raw POST body (for REST APIs) ──────────
// When receiving JSON from a frontend (fetch/axios) - not form submissions
$rawBody = file_get_contents("php://input");
$jsonData = json_decode($rawBody ?: "", associative: true, flags: JSON_THROW_ON_ERROR);
// ── php://memory - in-memory file (no disk I/O) ────────────────
$memHandle = fopen("php://memory", "r+b");
fwrite($memHandle, "header1,header2
val1,val2
");
rewind($memHandle);
while (($row = fgetcsv($memHandle)) !== false) {
// Process CSV from memory
}
fclose($memHandle);
// ── php://temp - memory then disk (for large intermediary data) ─
$tmp = fopen("php://temp/maxmemory:5242880", "r+b"); // 5MB in RAM, then disk
fwrite($tmp, $largeContent);
rewind($tmp);
$content = stream_get_contents($tmp);
fclose($tmp);
// ── Stream copying - memory efficient ─────────────────────────
$source = fopen("https://example.com/large-file.gz", "rb", context: $context);
$destination = fopen("/storage/downloads/file.gz", "wb");
stream_copy_to_stream($source, $destination);
fclose($source);
fclose($destination);Quick Quiz
Tip
Tip
Practice PHP Streams Stream Wrappers Context in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for PHP Streams - Stream Wrappers & Context
Practice Task
Note
Practice Task - (1) Write a working example of PHP Streams Stream Wrappers Context from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with PHP Streams Stream Wrappers Context is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.
Finished this lesson?