Streams allow you to read and write data in a memory-efficient way. PHP has built-in support for streams, but the syntax is clunky, and it requires a bit of boilerplate code to work with. Aphiria wraps PHP's streaming functionality into a simple interface: Aphiria\IO\Streams\IStream. Creating a stream is easy.

use Aphiria\IO\Streams\Stream;

$stream = new Stream(fopen('path/to/file', 'r+b'));

Reading from a Stream

You can read chunks of data from a stream via

// Read 64 bytes from the stream

You can also read to the end of a stream via


Note: This will read to the end of the stream from the current cursor position. To read the entire stream from the beginning, use (string)$stream.

Writing to a Stream

To write to a stream, call



To seek to a specific point in the stream, call

// Seek to the 1024th byte

To rewind to the beginning, you can call


Getting the Length of a Stream

To get the length of a stream, call


If it is not knowable, then getLength() will return null.

Note: If you happen to know the length of the stream ahead of time, you can pass it into the constructor, eg new Stream(fopen('path/to/file', 'r+b'), 2056). If you write anything to the stream, then the length is recalculated.

Copying to Another Stream

Sometimes, you'll need to copy one stream to another. One example would be writing a response body's stream to the php://output stream. You can do this via

$destinationStream = new Stream(fopen('php://output', 'r+b'));
$sourceStream = new Stream(fopen('path/to/file', 'r+b'));

Note: Copying to a stream does not rewind the source or destination streams. If you want to write the entire source stream to the destination, then call $sourceStream->rewind() prior to $sourceStream->copyToStream().

Closing a Stream

You can close a stream via


Note: When PHP performs garbage collection, close() is automatically called by the destructor.


In some cases, such as multi-part requests, you may need to append multiple streams together, yet treat them like a single stream. This is where MultiStream comes in handy:

use Aphiria\IO\Streams\MultiStream;
use Aphiria\IO\Streams\Stream;

$stream1 = new Stream('php://temp', 'r+b');
$stream2 = new Stream('php://temp', 'r+b');

$multiStream = new MultiStream();
echo (string)$multiStream; // "foobar"