Skip to content
Tutorials Center
My learning

Topics

Lesson 70 of 147 ยท Working with Files

Streams and Wrappers

Learn how PHP streams work - php://stdin, php://memory and php://temp, data:// URLs, gzip with compress.zlib://, stream filters, contexts and custom filters.

Every time you call fopen(), file_get_contents() or fgets(), PHP is working with a stream: a source or destination of bytes that you read from or write to in order. A file on disk is a stream, but so is the program's standard input, a block of memory, a gzip-compressed file, a web page fetched over HTTP, and a string embedded in a URL. PHP gives all of them the same function API, so code written for one usually works for the others unchanged.

What decides the kind of stream is the wrapper, the part of the path before ://. file:// (the default) means the local file system, php:// gives access to special streams such as memory buffers, compress.zlib:// compresses and decompresses transparently, and http:// fetches from the web. On top of that, filters can transform data as it flows through a stream, and contexts pass options to a wrapper.

This lesson builds directly on Reading and Writing Files. Once streams click, a lot of PHP suddenly looks simpler: reading uploaded JSON, writing CSV to a string, testing file-handling code without real files, and processing compressed logs all use the same few functions.

Wrappers: one API, many sources

You can ask PHP which wrappers it knows about. Each one is a protocol name you can put in front of ://:

PHP Listing stream wrappers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The list in the output depends on how PHP was built and which extensions are loaded, but php, file, data, http, compress.zlib and phar are almost always there. Here's what the common ones do:

Wrapper What it accesses
file:// Local files (the default when there's no prefix)
php:// Standard input/output/error, memory and temp buffers, the raw request body, filters
data:// Data embedded in the URL itself (RFC 2397 data: URLs)
compress.zlib://, compress.bzip2:// Gzip or bzip2 files, decompressed while reading and compressed while writing
http://, https:// Web resources (read-only; needs allow_url_fopen)
ftp://, ftps:// FTP servers
phar:// Files inside a PHP archive
zip:// Files inside a zip archive (from the zip extension)
glob:// Directory listings matching a pattern

The php:// streams

The php:// wrapper offers a handful of special streams. You'll use these constantly.

php://stdin, php://stdout, php://stderr

A command-line script has three standard streams: input, output and error output. The CLI defines the constants STDIN, STDOUT and STDERR as ready-made handles for them, and php://stdin and friends open new handles to the same streams. Our editor's Input box is fed to standard input, so this example reads from it:

PHP Reading standard input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

fgets() returns false at the end of input, which ends the loop. echo writes to the same output, so fwrite(STDOUT, ...) and echo are interchangeable in a CLI script. The difference shows up in error messages: anything you write to STDERR goes to the error stream, which shells let you redirect separately (php report.php 2> errors.log). The Command-Line PHP lesson covers this in depth.

There's also php://output, which writes through PHP's output layer exactly like echo (so it respects output buffering), and php://input, which on a web server gives you the raw request body. That's how an API reads a JSON payload: json_decode(file_get_contents('php://input'), true). You'll use it in Building a JSON API.

php://memory and php://temp

php://memory is a stream backed by RAM: you write to it, rewind, and read back, like a file that never touches the disk. php://temp behaves the same but switches to a real temporary file once the data grows beyond a limit (2 MB by default, or whatever you set with /maxmemory:<bytes>). Use php://temp whenever the data might be large.

These are perfect when a function insists on a stream handle but you want a string. fputcsv(), for example, only writes to handles. Point it at memory, and you get CSV text with correct quoting:

PHP Building CSV in memory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The comma in Notebook, A5 and the quotes in "dot grid" were quoted and escaped automatically. Two habits matter here:

  • Rewind before reading. After writing, the position is at the end of the stream, so reading immediately returns nothing. rewind($handle) (or fseek($handle, 0)) moves back to the start.
  • Use stream_get_contents() to read everything from the current position to the end. It's the handle-based equivalent of file_get_contents().

Passing escape: '' turns off PHP's non-standard backslash escaping in CSV, which is recommended for new code (see CSV Files).

Memory streams are a great tool for testing. A function that accepts a handle (function exportOrders($handle, array $orders)) can write to a real file in production and to php://memory in a test, where you rewind and check the output. Designing functions to take handles instead of file names makes them far easier to test.

data:// URLs

A data: URL carries its content inside the URL itself: a media type, an optional ;base64 marker, then the data. PHP reads them with the data:// wrapper (the short form data: works too). They're handy for tests, for small fixed inputs, and for treating a string as a file:

PHP Reading data URLs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

data:// streams are read-only. To get a writable in-memory stream, use php://memory.

Compressed files with compress.zlib://

Prefix a path with compress.zlib:// and PHP compresses everything you write in gzip format and decompresses everything you read. Your code still calls plain fopen(), fwrite() and fgets(), so a log processor can read access.log and access.log.gz with the same loop:

PHP Writing and reading a gzip file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Repetitive text like logs compresses extremely well, as the sizes show. Notice that filesize() gets the real path of the .gz file without the wrapper: asking for the size through compress.zlib:// isn't supported, because the uncompressed size isn't known without reading everything. If you just need to compress a string in memory, gzencode() and gzdecode() do it without any stream.

Stream filters

A filter transforms data as it passes through a stream. PHP has built-in filters for changing case (string.toupper, string.tolower), ROT13, Base64 and quoted-printable encoding (convert.base64-encode, convert.base64-decode, ...), compression (zlib.deflate, zlib.inflate) and character set conversion (convert.iconv.*). stream_get_filters() lists what's available.

You can attach filters in two ways. stream_filter_append() adds one to a handle you already have, for reading, writing or both. The php://filter wrapper applies filters to a whole resource in a URL, which makes it work with file_get_contents() and file_put_contents() too:

PHP Built-in stream filters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The filter chain string.tolower|convert.base64-encode runs from left to right: the text is lowercased, then Base64-encoded, and only the result reaches the file.

php://filter is also a classic attack tool. If an application passes user input to include or file_get_contents() (for example include $_GET['page']), an attacker can request php://filter/convert.base64-encode/resource=config.php and read your source code and passwords. Never build file paths from raw user input; the secure coding checklist shows how to whitelist them.

Writing your own filter

A custom filter is a class that extends php_user_filter and implements filter(). PHP hands it buckets of data; you take each bucket from $in, change its data, add the length to $consumed, and pass it on to $out. Register the class under a name with stream_filter_register() and use it like any built-in filter:

PHP A custom filter that masks card numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Every line written to the log passes through the filter, so the card numbers never reach the stream in full, while the short order numbers are left alone. One caveat for real code: a filter sees data in chunks, and a number could in theory be split across two buckets. Filters that must match patterns reliably buffer partial data until $closing is true.

Stream contexts

A context is a bundle of options for a wrapper, created with stream_context_create() and passed as an extra argument to fopen(), file_get_contents() and friends. The most common use is HTTP: setting the method, headers, body and timeout for a request. Our editor has no network access, so this example is read-only:

PHP
<?php
$context = stream_context_create([
    'http' => [
        'method' => 'POST',
        'header' => "Content-Type: application/json\r\nAccept: application/json\r\n",
        'content' => json_encode(['title' => 'Learn streams']),
        'timeout' => 5,
        'ignore_errors' => true,   // return the body even for 4xx/5xx responses
    ],
]);

$body = file_get_contents('https://api.example.com/tasks', false, $context);

// The response headers arrive via http_get_last_response_headers() (PHP 8.4+);
// older code used the magic $http_response_header variable.
$headers = http_get_last_response_headers();
echo $headers[0] ?? 'no response', "\n";   // e.g. "HTTP/1.1 201 Created"

Contexts work for other wrappers too: the ssl options control certificate checks for https://, and ftp options control things like overwriting. For anything beyond simple requests (retries, cookies, parallel requests), the curl extension or an HTTP client library is a better choice; you'll see both in Building a JSON API.

Remote URLs only work when allow_url_fopen is enabled in php.ini (it is by default). Including remote code with include 'http://...' is controlled by a separate setting, allow_url_include, which is off by default and must stay off.

Inspecting a stream

stream_get_meta_data() tells you what a handle is: its wrapper, stream type, mode, whether it's seekable, and whether you've hit the end. That's useful for debugging and for code that accepts "any handle":

PHP Stream metadata

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

A local file reports the plainfile wrapper and the STDIO stream type, and a data URL reports RFC2397, the standard that defines data: URLs. Memory and temp streams always report the mode w+b, whatever mode you opened them with, because they're always readable and writable.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You wrote three lines to a php://memory handle and then called stream_get_contents() immediately. It returned an empty string. Why?

    Writing moves the position to the end, and reading continues from the current position. rewind() moves back to the start so the data can be read.
  2. 2. What is the difference between php://memory and php://temp?

    Both start in RAM, but php://temp switches to a temporary file after 2 MB by default (configurable with /maxmemory:), so it is safer for data that might be large.
  3. 3. What does this print? echo file_get_contents('php://filter/read=string.toupper/resource=data://text/plain,abc');

    php://filter reads the resource (here a data URL containing abc) and passes it through the string.toupper filter, so the result is ABC.
  4. 4. How do you make fopen() transparently compress what you write in gzip format?

    The compress.zlib:// wrapper compresses on write and decompresses on read, so the rest of the code uses the normal stream functions.
  5. 5. Which stream gives a PHP script on a web server the raw body of the incoming HTTP request, such as a JSON payload?

    php://input is the raw request body. php://stdin is the CLI's standard input, and php://output writes to the response.

Summary

  • A stream is a source or destination of bytes; the same functions (fopen, fgets, fwrite, file_get_contents, stream_get_contents) work on all of them.
  • The wrapper before :// chooses the kind of stream: file://, php://, data://, compress.zlib://, http:// and more (stream_get_wrappers()).
  • STDIN/STDOUT/STDERR and php://stdin|stdout|stderr are the CLI's standard streams; php://input is the web request body; php://output writes like echo.
  • php://memory and php://temp are in-memory files; remember to rewind() before reading, and prefer php://temp for large data.
  • data:// URLs embed content in the path; compress.zlib:// reads and writes gzip transparently.
  • Filters transform data in flight (stream_filter_append(), php://filter/read=...|.../resource=...), and you can write your own by extending php_user_filter.
  • Contexts (stream_context_create()) pass options such as HTTP method, headers and timeouts to a wrapper.

Next: Working with Images: GD.