2 min read

PHP Streams

Streams in PHP are a way of generalizing file, network, data compression, and other operations which share a common set of functions and uses. In its simplest definition, a stream is a resource object which exhibits streamable behavior. That is, it can be read from or written to in a linear fashion, and it may be able to fseek() to an arbitrary location within the stream.

Stream Wrappers

Streams are accessed via wrappers. A wrapper is a piece of code that tells the stream how to handle different protocols. PHP provides a number of built-in wrappers, such as:

  • file:// — Accessing local filesystem
  • http:// — Accessing HTTP(s) URLs
  • ftp:// — Accessing FTP(s) URLs
  • php:// — Accessing various I/O streams
  • zlib:// — Compression Streams
  • data:// — Data (RFC 2397)

For example, you can use file_get_contents() to read a file from the local filesystem or from a URL:

<?php
// Read from a local file
$content = file_get_contents('file://path/to/file.txt');

// Read from a URL
$content = file_get_contents('http://example.com');
?>

php:// Streams

The php:// wrapper provides access to various I/O streams. Some of the most common are:

  • php://stdin: A read-only stream that allows you to read from the standard input.
  • php://stdout: A write-only stream that allows you to write to the standard output.
  • php://stderr: A write-only stream that allows you to write to the standard error.
  • php://input: A read-only stream that allows you to read the raw request body. This is useful for handling POST requests with a content type other than application/x-www-form-urlencoded.
  • php://output: A write-only stream that allows you to write to the output buffer in the same way as echo or print.
  • php://memory: A read/write stream that stores data in memory.
  • php://temp: A read/write stream that stores data in memory, but will switch to a temporary file if the size exceeds a certain limit.

Stream Contexts

Stream contexts allow you to pass options and parameters to stream wrappers. This is often used to configure how a stream is opened or to modify its behavior.

<?php
$options = [
    'http' => [
        'method' => 'POST',
        'header' => "Content-type: application/x-www-form-urlencoded\r\n",
        'content' => http_build_query(['foo' => 'bar']),
    ],
];

$context = stream_context_create($options);

$result = file_get_contents('http://example.com/submit', false, $context);
?>

Custom Stream Wrappers

You can also create your own custom stream wrappers using the stream_wrapper_register() function and creating a class that implements the streamWrapper interface. This allows you to create your own protocols and handle them in a stream-like fashion.