stream-interop / interface
Interoperable interfaces for streams in PHP 8.4 and later.
Requires
- php: >=8.4
Requires (Dev)
- pds/composer-script-names: ^1.0
- pds/skeleton: ^1.0
- phpstan/phpstan: ^2.0
- pmjones/php-styler: 0.x@dev
- star-interop/stardoc: 1.x-dev
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-30 20:12:56 UTC
README
Stream-Interop provides an interoperable package of standard interfaces for working with stream resources in PHP 8.4 or later. It reflects, refines, and reconciles the common practices identified within several pre-existing projects.
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in BCP 14 (RFC 2119, RFC 8174).
This package attempts to adhere to the Package Development Standards approach to naming and versioning.
Interfaces
Stream-Interop defines separate interfaces for various affordances around stream resources so that (1) implementations can advertise well-tailored affordances, and (2) consumers can typehint to the specific affordances they require for specific situations.
-
Stream is a common baseline for streams.
-
ResourceStream extends Stream to afford direct access to the encapsulated resource.
-
ClosableStream extends Stream to afford closing the stream.
-
SizableStream extends Stream to afford getting the full length of the stream in bytes.
-
ReadableStream extends Stream to afford non-idempotent reading from the stream.
-
SeekableStream extends Stream to afford moving the stream pointer position back and forth.
-
StringableStream extends Stream to afford idempotent reading from the encapsulated resource.
-
WritableStream extends Stream to afford writing to the stream at the current pointer position.
-
ReadonlyStream is a marker interface that extends Stream to indicate the implementation attempts to enforce readonly constraints on the encapsulated resource.
-
ImmutableStream extends ReadonlyStream and StringableStream to indicate the implementation attempts to enforce immutability constraints on the encapsulated resource.
-
StreamThrowable is a marker interface that extends Throwable to indicate an Exception is stream-related.
-
StreamTypeAliases defines custom PHPStan types to aid static analysis.
Stream
Stream is a common baseline for streams.
-
Notes:
-
The
$metadataproperty is expected to change dynamically. That is, as the encapsulated resource gets read from and written to, the metadata for that resource is likely to change. Thus, the$metadataproperty value is expected to change along with it. In practical terms, this likely means astream_get_meta_data()call on each access of$metadata. -
There are no
isReadable(), etc. methods. If necessary, such functionality can be determined by typehinting against the interface, or by checkinginstanceof, etc. -
The encapsulated resource is not exposed publicly here. The encapsulated resource may remain private or protected. See the ResourceStream interface for details on making the encapsulated resource publicly accessible.
-
Cloning shares the encapsulated resource. Consumers might expect a cloned stream to be independent of the original. However, PHP copies the property that holds the resource, so the original and the clone share one resource, with one pointer and one open-or-closed state; closing the clone also closes the original. An implementation that needs independent clones can copy the resource in
__clone(). -
Serializing does not preserve the resource. Consumers might expect
unserialize(serialize($stream))to give an equivalent stream. However, PHP serializes a resource as the integer0, so the unserialized stream has no resource at all. An implementation can refuse serialization by throwing from__serialize()and__unserialize(), or can serialize what it needs to reopen the resource, such as a file name.
-
Stream Properties
-
public metadata_array $metadata { get; }
-
Represents the metadata for the encapsulated resource as if by
stream_get_meta_data(). -
Directives:
-
Implementations MUST provide the most-recent metadata for the encapsulated resource at the moment of property access; if the encapsulated resource is closed, implementations MUST return an empty array.
-
Implementations MUST NOT allow
$metadatato be publicly settable, either as a property or via property hook or method.
-
-
Notes:
-
PHP judges a
modeby its first character and any+. Implementations might treat a resource as readable when itsmodecontains anr, and as writable when it contains aw. However,rwopens a file read-only, andwropens it write-only. So a resource is readable when itsmodestarts withror contains+, and writable when it starts withw,a,x, orc, or contains+. -
The closed-stream empty array is not a
metadata_array. Implementors might expect PHPStan to accept the[]that a closed stream returns. However,metadata_arrayrequires most of its keys, so a hook declared@var metadata_arrayfails onreturn []. An implementation can leave the hook's type to@inheritdoc, so that PHPStan checks what the hook returns against a plainarray; reads of$metadatakeep themetadata_arraytype.
-
-
Stream Methods
-
public function isClosed() : bool;
- Returns
trueif the encapsulated resource has been closed, orfalseif not.
- Returns
-
public function isOpen() : bool;
- Returns
trueif the encapsulated resource is still open, orfalseif not.
- Returns
ResourceStream
ResourceStream extends Stream to afford direct access to the encapsulated resource.
-
Notes:
-
Not all Stream implementations need to expose the encapsulated resource. Exposing the resource gives full control over it to consumers, who can then manipulate it however they like (e.g. close it, move the pointer, and so on). However, having access to the resource may be necessary for some consumers.
-
Some Stream implementations might not encapsulate a resource. Although a resource is the most common data source for a stream, other data sources may be used, in which cases ResourceStream implementation is neither appropriate nor necessary.
-
ResourceStream Properties
-
public resource $resource { get; }
-
Represents the resource as if opened by
fopen(),fsockopen(),popen(), etc. -
Directives:
-
Implementations MUST ensure
$resourceis aresource of type (stream); for example, as determined byget_resource_type(). -
Implementations SHOULD NOT allow
$resourceto be publicly settable, either as a property or via property hook or method.
-
-
Notes:
- A closed resource is no longer of type
(stream). Consumers might expect$resourceto stay aresource of type (stream)for the life of the ResourceStream. However, once the resource is closed, whether by ClosableStream or by a consumer callingfclose()on it,get_resource_type()reportsUnknown. So after closing,$resourceholds a closed resource, andisOpen()tells the two apart.
- A closed resource is no longer of type
-
ClosableStream
ClosableStream extends Stream to afford closing the stream.
-
Directives:
- Implementations MAY close the encapsulated resource internally without affording ClosableStream.
-
Notes:
ClosableStream Methods
-
public function close() : void;
-
Closes the encapsulated resource as if by
fclose(),pclose(), etc. -
Directives:
-
Implementations MUST throw a StreamThrowable on failure.
-
Implementations SHOULD NOT throw when the encapsulated resource is already closed.
-
-
Notes:
- A repeated
close()can still throw. Consumers might expect closing an already-closed stream to do nothing, as the directive advises and most projects in the Stream-Interop research do. However,fclose()on a closed resource throws a TypeError, so some implementations treat a repeatedclose()as a failure and throw a StreamThrowable. A consumer that may close a stream twice can checkisClosed()first, and so can an implementation before it callsfclose().
- A repeated
-
SizableStream
SizableStream extends Stream to afford getting the full length of the stream in bytes.
-
Directives:
- Implementations MAY get the size of the encapsulated resource internally without affording SizableStream.
-
Notes:
- Not all Stream implementations need to be sizable. Some encapsulated resources may be unable to report a size; for example, remote or write-only resources.
SizableStream Methods
-
public function getSize() : ?int<0,max>;
-
Returns the length of the encapsulated resource in bytes as if by the
fstat()value forsize, ornullif indeterminate or on error. -
Notes:
- A pipe or socket has no length. Consumers might expect
getSize()to report how many bytes a stream holds. However,fstat()reports a pipe or socket as something other than a regular file, and itssizethere is0, or on some platforms the number of bytes buffered so far (e.g.,5for apopen()pipe that has receivedhello, then0once that has been read). An implementation can returnnullfor such a resource, since its size is indeterminate.
- A pipe or socket has no length. Consumers might expect
-
ReadableStream
ReadableStream extends Stream to afford non-idempotent reading from the stream.
-
Directives:
-
If the encapsulated resource is not readable at the time it becomes available to the ReadableStream, implementations MUST throw a StreamThrowable.
-
Implementations MAY read from the encapsulated resource internally without affording ReadableStream.
-
-
Notes:
-
The
eof()method is on ReadableStream, not Stream or SeekableStream. End-of-file is determined as a function of reading past the end of the file, not as of seeking to the end of the file. Cf. https://www.php.net/manual/en/function.feof.php#122925. -
These methods are non-idempotent. They may return different results on repeated sequential calls, and may have side effects (e.g., changing the position of the pointer.)
-
ReadableStream Methods
-
public function eof() : bool;
-
Tests for end-of-file on the encapsulated resource as if by
feof(). -
Directives:
- Implementations MUST throw a StreamThrowable on failure.
-
-
public function read(int<1,max> $length) : string;
-
Returns up to
$lengthbytes from the encapsulated resource as if byfread(). -
Directives:
- Implementations MUST throw a StreamThrowable on failure.
-
Notes:
-
The
int<1,max>type is not enforced at runtime. Implementors might expect the type to keep zero and negative lengths out. However, the native type isint, so a caller without static analysis can pass any integer, andfread()rejects a length below1with a ValueError, which is not a StreamThrowable. An implementation can check the length itself and throw a StreamThrowable; declaring@param int $lengthon the implementing method keeps PHPStan from reporting that check as dead code. -
A huge
$lengthcan exhaust memory. Consumers might expectread(PHP_INT_MAX)to return whatever remains. However,fread()allocates$lengthbytes before reading, so a huge length is a fatal error, whichcatchcannot intercept. On a seekable resource,stream_get_contents()with a length of 32 KB or more returns up to that many bytes without that allocation; on a blocking pipe or socket it waits until that many bytes arrive, the resource reaches end-of-file, or a read times out. There, an implementation can make a singlefread()of a bounded length, which on a socket, or on a pipe frompopen()orproc_open(), returns as soon as some bytes are available.
-
-
-
public function getContents() : string;
-
Returns the remaining contents of the resource from the current pointer position as if by
stream_get_contents(). -
Directives:
- Implementations MUST throw a StreamThrowable on failure.
-
SeekableStream
SeekableStream extends Stream to afford moving the stream pointer position back and forth.
-
Directives:
- If the encapsulated resource is not seekable at the time it becomes available to the SeekableStream, implementations MUST throw a StreamThrowable.
SeekableStream Methods
-
public function rewind() : void;
-
Moves the stream pointer position to the beginning of the stream as if by
rewind(). -
Directives:
- Implementations MUST throw a StreamThrowable on failure.
-
-
public function seek( int $offset, SEEK_CUR|SEEK_SET|SEEK_END $whence = SEEK_SET, ) : void;
-
Moves the stream pointer position to the
$offsetas if byfseek(). -
Directives:
- Implementations MUST throw a StreamThrowable on failure.
-
Notes:
-
The
SEEK_CUR|SEEK_SET|SEEK_ENDtype is not enforced at runtime. Implementors might expect the type to keep other$whencevalues out. However, the native type isint, so a caller without static analysis can pass any integer, andfseek()does not always reject it; for example, on macOS a plain file accepts a$whenceof3or4and moves the pointer, whilephp://memoryrefuses both. An implementation can check$whenceitself and throw a StreamThrowable; declaring@param int $whenceon the implementing method keeps PHPStan from reporting that check as dead code. -
A failed seek can move the pointer. Consumers might expect a failed seek to leave the pointer where it was. However, on some streams a failed
fseek()leaves the pointer elsewhere; for example, afterfseek($resource, -100, SEEK_END)fails on a 5-bytephp://memoryresource,ftell()returnsfalse, and the next read starts from the beginning. An implementation can note the position and the end-of-file state before seeking, and restore them when the seek fails.
-
-
-
public function tell() : int;
-
Returns the current stream pointer position as if by
ftell(). -
Directives:
- Implementations MUST throw a StreamThrowable on failure.
-
StringableStream
StringableStream extends Stream to afford idempotent reading from the encapsulated resource.
-
Directives:
-
If the encapsulated resource is not readable at the time it becomes available to the StringableStream, implementations MUST throw a StreamThrowable.
-
If the encapsulated resource is not seekable at the time it becomes available to the StringableStream, implementations MUST throw a StreamThrowable.
-
Implementations MAY convert all or part of the encapsulated resource to a string internally without affording StringableStream.
-
-
Notes:
-
These methods are idempotent. Repeated sequential calls to an unchanged resource will return the exact same result, without exposing side effects (such as the pointer position being changed).
-
A stateful read filter changes the resource on each read. Consumers might expect repeated idempotent reads to return the same result whatever filters the resource carries. However, a filter appended for reading stays attached and keeps its state when the pointer moves, so a stateful filter leaves the resource changed after each read. For example, with
zlib.deflateappended as a read filter, a first__toString()returns the compressed contents, and a second returns an empty string. -
Repositioning the pointer clears the end-of-file state. Implementors might expect that seeking back to the initial location undoes an idempotent read. However,
fseek()clears the end-of-file indicator even when seeking to the current position, so a stream that was at end-of-file would no longer report it. An implementation can restore the state by reading one byte after the final seek when the stream was at end-of-file beforehand, and seeking back again if that read returns a byte.
-
StringableStream Methods
-
public function __toString() : string;
-
Returns the entire contents of the encapsulated resource as if by
rewind()ing before returningstream_get_contents(). -
Directives:
-
After reading, implementations MUST reposition the encapsulated resource pointer to its initial location.
-
Implementations MUST throw a StreamThrowable on failure.
-
-
-
public function subString(int $offset, ?int<0,max> $length = null) : string;
-
Returns a string from the encapsulated resource as if by
fseek()ing before reading. -
Directives:
-
If the
$offsetis negative, implementations MUST begin reading at that many bytes from the end of the stream; otherwise, implementations MUST begin reading at that many bytes from the start of the stream. -
If the
$lengthis null, implementations MUST return all remaining bytes from the stream; otherwise, implementations MUST return up to that many bytes from the stream. -
After reading, implementations MUST reposition the encapsulated resource pointer to its initial location.
-
Implementations MUST throw a StreamThrowable on failure.
-
-
Notes:
- The
?int<0,max>type is not enforced at runtime. Implementors might expect the type to keep negative lengths out. However, the native type is?int, so a caller without static analysis can pass a negative length;stream_get_contents()reads-1as all remaining bytes, and rejects a lower length with a ValueError, which is not a StreamThrowable. An implementation can check the length itself and throw a StreamThrowable; declaring@param ?int $lengthon the implementing method keeps PHPStan from reporting that check as dead code.
- The
-
WritableStream
WritableStream extends Stream to afford writing to the stream at the current pointer position.
-
Directives:
-
If the encapsulated resource is not writable at the time it becomes available to the WritableStream, implementations MUST throw a StreamThrowable.
-
Implementations MAY write to the encapsulated resource internally without affording WritableStream.
-
-
Notes:
- Append mode ignores the pointer. Consumers might expect
write()to write at the current pointer position. However, PHP writes to a resource opened inaora+mode at the end, wherever the pointer is, andftell()can then report a position other than where the write happened; for example, afterfseek(0)andfwrite('X')on a 5-bytea+file, the file ends inX, yetftell()reports1.
- Append mode ignores the pointer. Consumers might expect
WritableStream Methods
-
public function write(string|Stringable $data) : int;
-
Writes
$datastarting at the current stream pointer position, returning the number of bytes written, as if byfwrite(). -
Directives:
- Implementations MUST throw a StreamThrowable on failure.
-
ReadonlyStream
ReadonlyStream is a marker interface that extends Stream to indicate the implementation attempts to enforce readonly constraints on the encapsulated resource.
-
Directives:
-
Implementations MUST open the encapsulated resource inside the ReadonlyStream.
-
Implementations MUST open the encapsulated resource as
php://inputorphp://memory. -
Implementations MAY open the encapsulated resource in a mode that allows writing (
rb+,w+, etc.) to allow initialization. -
Implementations MAY initialize the encapsulated resource after opening (e.g., by copying a constructor argument to the encapsulated resource).
-
Implementations MUST NOT modify, or allow modification of, the encapsulated resource content after initialization, whether by implementing WritableStream or by some other means.
-
Implementations MUST NOT expose the encapsulated resource, whether by implementing ResourceStream or by some other means.
-
Implementations MAY allow closing of the encapsulated resource, whether by implementing ClosableStream or by some other means.
-
-
Notes:
-
The readonly constraints are necessarily strict. Whereas readonly on scalar and array properties can be implemented relatively easily, readonly on a resource property is more difficult. The encapsulated resource, including both its content and its pointer, must be inaccessible from outside the ReadonlyStream (e.g., through a resource passed to its constructor) to ensure it cannot be modified from outside the ReadonlyStream. Its own methods, such as those of ReadableStream and SeekableStream, can still move the pointer.
-
ReadonlyStream implementations may be memory-intensive. This is because they usually have to be initialized with a copy of the original resource, typically a file resource, thereby reading all of it into a
php://memoryresource. -
The implementation chooses how to make a copy. Implementors might expect ReadonlyStream to specify where and how to copy a caller's resource. However, the directives govern only the encapsulated resource, which is the copy, so those choices are the implementation's. A constructor or a static factory method of the class can make the copy. The copy can hold all of a seekable resource, with the caller's pointer restored afterward, or the rest of the resource from its pointer onward, with the caller's pointer left at the end.
-
php://tempcan move a copy to disk. Implementors might reach forphp://tempto save memory. However, once its content reaches a limit (2 MB by default),php://tempmoves the content into a file in the system temporary directory, where code outside the ReadonlyStream could modify it.php://memorynever moves its content to disk. -
php://inputis natively readonly. It does not need to be copied to aphp://memoryresource, and does not need to be initialized. -
A large request body may be kept on disk. Implementors might expect
php://inputto be as far out of reach as aphp://memorycopy. However, PHP may keep a large request body in a temporary file; under the built-in web server, a 300 KB body was kept in the system temporary directory, and writing to that file changed whatphp://inputreturned. An implementation that needs the stronger guarantee can copyphp://inputintophp://memory. -
php://inputcan seek only within what PHP has read. Implementors might expect to seek anywhere in the request body. However, for aPUT,PATCH, or other non-POSTrequest, or aPOSTwithenable_post_data_readingoff, PHP reads the body only as the script readsphp://input, andfseek()reaches only the part PHP has read so far; for example, under CGI and the built-in web server,fseek($resource, -5, SEEK_END)failed on a freshly openedphp://inputfor aPUTrequest. Once the whole body has been read, seeking reaches all of it, so an implementation can read the whole body before its first seek.
-
ImmutableStream
ImmutableStream extends ReadonlyStream and StringableStream to indicate the implementation attempts to enforce immutability constraints on the encapsulated resource.
-
Directives:
-
Implementations MUST adhere to all ReadonlyStream constraints.
-
Implementations MUST NOT allow non-idempotent reading of the encapsulated resource, whether by implementing ReadableStream or by some other means.
-
Implementations MUST NOT expose the state of the encapsulated resource pointer, whether by implementing SeekableStream or by some other means.
-
Implementations MUST NOT allow closing of the encapsulated resource before the ImmutableStream is destructed, whether by implementing ClosableStream or by some other means.
-
Implementations MUST NOT allow mutation of the
$metadataproperty.
-
-
Notes:
-
The immutability constraints are necessarily strict. Immutability of a resource is incompatible with non-idempotent reading; doing so modifies its pointer position, thereby changing its state. Likewise, closing the resource changes its state. These constraints leave only StringableStream and SizableStream as compatible interfaces.
-
The
$metadatacan be captured once. Implementors might expect to fetch$metadataanew on each access, as the Stream directive describes. However, nothing about an immutable resource changes, as long as its idempotent reads also restore the end-of-file state (see StringableStream), so metadata captured at construction remains the most-recent metadata. This matters for areadonlyclass, since PHP does not allow hooks on readonly properties; such an implementation can capture$metadatainto a readonly property instead. -
Reporting
eofandunread_bytesdoes not expose the pointer. Implementors might expect those keys of$metadatato expose the state of the pointer, since both reflect it. However, like the rest of the metadata, they keep the values they had at construction (falseand0for aphp://memorycopy or forphp://input), so a consumer sees no movement of the pointer. -
Closing on destruct breaks clones. Implementors might close the encapsulated resource in
__destruct(), since closing before then is not allowed. However, a clone shares the resource, so destroying one clone would close the resource of every other. PHP frees the resource once the last stream holding it is gone, so an ImmutableStream need not close it at all.
-
StreamThrowable
StreamThrowable is a marker interface that extends Throwable to indicate an Exception is stream-related.
It adds no class members.
StreamTypeAliases
StreamTypeAliases defines custom PHPStan types to aid static analysis.
-
metadata_array: array{ timed_out: bool, blocked: bool, eof: bool, unread_bytes: int, stream_type: string, wrapper_type: string, wrapper_data: mixed, mode: string, seekable: bool, uri?: string, mediatype?: string, base64?: bool, crypto?: array{ protocol: string, cipher_name: string, cipher_bits: int, cipher_version: string, alpn_protocol?: string } }-
An
arrayof stream metadata, as if bystream_get_meta_data(). -
Some required keys can be missing. Consumers might expect every key the type requires to be present. However, PHP omits
timed_out,blocked, andeofforphp://tempanddata:resources,wrapper_typefor pipes and sockets, andwrapper_datafor most streams, so reading one of them can warn "Undefined array key". A consumer can read those keys with??and a default; PHPStan then reports the guard as unneeded, since the type marks the keys as required.
-
-
stat_array: array{ dev: int<0,max>, ino: int<0,max>, mode: int<0,max>, nlink: int<0,max>, uid: int<0,max>, gid: int<0,max>, rdev: int<0,max>, size: int<0,max>, atime: int<0,max>, mtime: int<0,max>, ctime: int<0,max>, blksize: int<0,max>, blocks: int<0,max> }
Implementations
Implementations MAY encapsulate a string, or some other kind of data source, instead of a resource.
Implementations encapsulating something besides a resource MUST behave as if they encapsulate a resource.
Implementations advertised as readonly or immutable MUST be deeply readonly or immutable. With the exception of implementations meeting the specified ReadonlyStream or ImmutableStream conditions, they MUST NOT encapsulate any references, resources, mutable objects, objects or arrays encapsulating references or resources or mutable objects, and so on.
Implementations MAY define additional class members not defined in these interfaces; implementations advertised as readonly or immutable MUST make those additional class members deeply readonly or immutable.
Notes:
-
Reflection does not invalidate advertisements of readonly or immutable implementations. The ability of a consumer to use Reflection to mutate an implementation advertised as readonly or immutable does not constitute a failure to comply with Stream-Interop.
-
(array)casts and similar means of introspection likewise do not invalidate such advertisements. An(array)cast exposes private and protected properties, including an encapsulated resource, which a consumer can then write to, seek, or close; doing that to an implementation advertised as readonly or immutable does not constitute a failure to comply with Stream-Interop. -
"Advertised as readonly or immutable" means implementing ReadonlyStream or ImmutableStream. An implementation does not take on the deeply readonly or immutable requirements by being a PHP
readonlyclass, or by describing itself as readonly in its documentation. -
Reference implementations are available at https://github.com/stream-interop/impl.
Q & A
What projects were used as reference points for Stream-Interop?
These are the reference projects for developing the above interfaces.
- amphp/byte-stream: https://github.com/amphp/byte-stream
- fzaninotto/streamer: https://github.com/fzaninotto/Streamer
- hoa/stream: https://github.com/hoaproject/Stream
- kraken-php/stream: https://github.com/kraken-php/stream
- psr/http-message: https://github.com/php-fig/http-message/blob/master/src/StreamInterface.php
- react/stream: https://packagist.org/packages/react/stream
- zenstruck/stream: https://github.com/zenstruck/stream
Please see README-RESEARCH.md for more information.
What about filters?
Stream filters are a powerful aspect of stream resources. However, as they operate on resources directly, creating interfaces for them is out-of-scope for Stream-Interop. Further, of the projects included in the Stream-Interop research, only hoa/stream offered stream filters, as a wrapper around PHP's own, making it difficult to rationalize adding filter interfaces.
Even so, consumers are free to register filters on the resources they inject into a Stream. In addition, implementors are free to create filter mechanisms that intercept the input going into a WritableStream (e.g. via its write() method) or the output coming from a ReadableStream (e.g. via its read() method).
A stateful read filter makes repeated idempotent reads differ; see StringableStream.
Why is there no Factory interface?
The sheer volume of possible combinations of the various interfaces makes it difficult to provide a factory with proper return typehints. Implementors are encouraged to develop their own factories with proper typehinting.