PHPackages                             amphp/byte-stream - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Queues &amp; Workers](/categories/queues)
4. /
5. amphp/byte-stream

ActiveLibrary[Queues &amp; Workers](/categories/queues)

amphp/byte-stream
=================

A stream abstraction to make working with non-blocking I/O simple.

v2.1.2(1y ago)393116.2M—4.3%28[2 issues](https://github.com/amphp/byte-stream/issues)[1 PRs](https://github.com/amphp/byte-stream/pulls)20MITPHPPHP &gt;=8.1CI failing

Since Jun 15Pushed 1mo ago5 watchersCompare

[ Source](https://github.com/amphp/byte-stream)[ Packagist](https://packagist.org/packages/amphp/byte-stream)[ Docs](https://amphp.org/byte-stream)[ GitHub Sponsors](https://github.com/amphp)[ RSS](/packages/amphp-byte-stream/feed)WikiDiscussions 2.x Synced 1mo ago

READMEChangelog (10)Dependencies (10)Versions (55)Used By (20)

amphp/byte-stream
=================

[](#amphpbyte-stream)

AMPHP is a collection of event-driven libraries for PHP designed with fibers and concurrency in mind. `amphp/byte-stream` specifically provides a stream abstraction to ease working with various byte streams.

Installation
------------

[](#installation)

This package can be installed as a [Composer](https://getcomposer.org/) dependency.

```
composer require amphp/byte-stream
```

Requirements
------------

[](#requirements)

This package requires PHP 8.1 or later.

Usage
-----

[](#usage)

Streams are an abstraction over ordered sequences of bytes. This package provides the fundamental interfaces `ReadableStream` and `WritableStream`.

> **Note**Previous versions used the terms `InputStream` and `OutputStream`, but these terms can be confusing depending on the use case.

### ReadableStream

[](#readablestream)

`ReadableStream` offers a primary method: `read()`. It returns a `string` or `null`. `null` indicates that the stream has ended.

The following example shows a `ReadableStream` consumption that buffers the complete stream contents.

```
$stream = ...;
$buffer = "";

while (($chunk = $stream->read()) !== null) {
    $buffer .= $chunk;
}

// do something with $buffer
```

> **Note**`Amp\ByteStream\buffer($stream)` can be used instead, but we'd like to demonstrate manual consumption here.

This package offers some basic implementations, other libraries might provide even more implementations, such as [`amphp/socket`](https://github.com/amphp/socket).

- [`Payload`](#payload)
- [`ReadableBuffer`](#readablebuffer)
- [`ReadableIterableStream`](#readableiterablestream)
- [`ReadableResourceStream`](#readableresourcestream)
- [`ReadableStreamChain`](#readablestreamchain)
- [`Base64DecodingReadableStream`](#base64decodingreadablestream)
- [`Base64EncodingReadableStream`](#base64encodingreadablestream)
- [`DecompressingReadableStream`](#decompressingreadablestream)

### Payload

[](#payload)

`Payload` implements `ReadableStream` while also providing a `buffer()` method for buffering the entire contents. This allows consuming a message either in chunks (streaming) or consume everything at once (buffering). When the object is destructed, any remaining data in the stream is automatically consumed and discarded. This class is useful for small payloads or when the entire contents of a stream is needed before any processing can be done.

#### Buffering

[](#buffering)

Buffering a complete readable stream can be accomplished using the `buffer()` method.

```
$payload = new Payload($inputStream);
$content = $payload->buffer();
```

#### Streaming

[](#streaming)

Sometimes it's useful / possible to consume a payload in chunks rather than first buffering it completely, e.g. streaming a large HTTP response body directly to disk.

```
while (null !== $chunk = $payload->read()) {
    // Use $chunk here, works just like any other ReadableStream
}
```

### ReadableBuffer

[](#readablebuffer)

An `ReadableBuffer` allows creating a `ReadableStream` from a single known string chunk. This is helpful if the complete stream contents are already known.

```
$stream = new ReadableBuffer("foobar");
```

It also allows creating a stream without any chunks by passing `null` as chunk / omitting the constructor argument:

```
$stream = new ReadableBuffer;

// The stream ends immediately
assert(null === $stream->read());
```

### ReadableIterableStream

[](#readableiterablestream)

`ReadableIterableStream` allows converting an `iterable` that yields strings into a `ReadableStream`:

```
$inputStream = new Amp\ByteStream\ReadableIterableStream((function () {
    for ($i = 0; $i < 10; $i++) {
        Amp\delay(1);
        yield $emit(".");
    }
})());
```

### ReadableResourceStream

[](#readableresourcestream)

This package abstracts PHP's stream resources with `ReadableResourceStream` and `WritableResourceStream`. They automatically set the passed resource to non-blocking mode and allow reading and writing like any other `ReadableStream` / `WritableStream`. They also handle backpressure automatically by disabling the read watcher in case there's no read request and only activate a writability watcher if the underlying write buffer is already full, which makes them very efficient.

### DecompressingReadableStream

[](#decompressingreadablestream)

This package implements compression based on Zlib. `CompressingWritableStream` can be used for compression, while `DecompressingReadableStream` can be used for decompression. Both can simply wrap an existing stream to apply them. Both accept an `$encoding` and `$options` parameter in their constructor.

```
$readableStream = new ReadableResourceStream(STDIN);
$decompressingReadableStream = new DecompressingReadableStream($readableStream, \ZLIB_ENCODING_GZIP);

while (null !== $chunk = $decompressingReadableStream) {
    print $chunk;
}
```

See also: [`./examples/gzip-decompress.php`](https://github.com/amphp/byte-stream/blob/v2/examples/gzip-decompress.php)

### WritableStream

[](#writablestream)

`WritableStream` offers two primary methods: `write()` and `end()`.

#### WritableStream::write

[](#writablestreamwrite)

`write()` writes the given string to the stream. Waiting for completion allows writing only as fast as the underlying stream can write and potentially send over a network. TCP streams will return immediately as long as the write buffer isn't full.

The writing order is always ensured, even if the writer doesn't wait for completion before issuing another write.

#### WritableStream::end

[](#writablestreamend)

`end()` marks the stream as ended. TCP streams might close the underlying stream for writing, but MUST NOT close it. Instead, all resources should be freed and actual resource handles be closed by PHP's garbage collection process.

The following example uses the previous example to read from a stream and writes all data to a `WritableStream`:

```
$readableStream = ...;
$writableStream = ...;
$buffer = "";

while (($chunk = $readableStream->read()) !== null) {
    $writableStream->write($chunk);
}

$writableStream->end();
```

> **Note**`Amp\ByteStream\pipe($readableStream, $writableStream)` can be used instead, but we'd like to demonstrate manual consumption / writing here.

This package offers some basic implementations, other libraries might provide even more implementations, such as [`amphp/socket`](https://github.com/amphp/socket).

- [`WritableBuffer`](#writablebuffer)
- [`WritableIterableStream`](#writableiterablestream)
- [`WritableResourceStream`](#writableresourcestream)
- [`Base64DecodingWritableStream`](#base64decodingwritablestream)
- [`Base64EncodingWritableStream`](#base64encodingwritablestream)
- [`CompressingWritableStream`](#compressingwritablestream)

### WritableResourceStream

[](#writableresourcestream)

This package abstracts PHP's stream resources with `ReadableResourceStream` and `WritableResourceStream`. They automatically set the passed resource to non-blocking mode and allow reading and writing like any other `ReadableStream` / `WritableStream`. They also handle backpressure automatically by disabling the read watcher in case there's no read request and only activate a writability watcher if the underlying write buffer is already full, which makes them very efficient.

### CompressingWritableStream

[](#compressingwritablestream)

This package implements compression based on Zlib. `CompressingWritableStream` can be used for compression, while `DecompressingReadableStream` can be used for decompression. Both can simply wrap an existing stream to apply them. Both accept an `$encoding` and `$options` parameter in their constructor.

```
$writableStream = new WritableResourceStream(STDOUT);
$compressedWritableStream = new CompressingWritableStream($writableStream, \ZLIB_ENCODING_GZIP);

for ($i = 0; $i < 100; $i++) {
    $compressedWritableStream->write(bin2hex(random_bytes(32));
}

$compressedWritableStream->end();
```

See also: [`./examples/gzip-compress.php`](https://github.com/amphp/byte-stream/blob/v2/examples/gzip-compress.php)

Versioning
----------

[](#versioning)

`amphp/byte-stream` follows the [semver](http://semver.org/) semantic versioning specification like all other `amphp` packages.

Security
--------

[](#security)

If you discover any security related issues, please email [`me@kelunik.com`](mailto:me@kelunik.com) instead of using the issue tracker.

License
-------

[](#license)

The MIT License (MIT). Please see [`LICENSE`](./LICENSE) for more information.

###  Health Score

72

—

ExcellentBetter than 100% of packages

Maintenance71

Regular maintenance activity

Popularity73

Solid adoption and visibility

Community43

Growing community involvement

Maturity85

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 51.4% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~54 days

Recently: every ~98 days

Total

53

Last Release

428d ago

Major Versions

v1.8.1 → v2.0.0-beta.12021-12-11

1.x-dev → v2.1.22025-03-16

PHP version history (3 changes)v1.8.0PHP &gt;=7.1

v2.0.0-beta.1PHP &gt;=8

v2.0.0-beta.6PHP &gt;=8.1

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/1628287?v=4)[Aaron Piotrowski](/maintainers/Trowski)[@trowski](https://github.com/trowski)

![](https://www.gravatar.com/avatar/12852217f3369e8144bc9ce6ac2a2341c28c5512c5b3df5749bfbbd45b6877ff?d=identicon)[kelunik](/maintainers/kelunik)

![](https://www.gravatar.com/avatar/f6db63ad594446f67d79532b75c69439fd0df779cc90868b43c187c02a4221ef?d=identicon)[bwoebi](/maintainers/bwoebi)

---

Top Contributors

[![kelunik](https://avatars.githubusercontent.com/u/2743004?v=4)](https://github.com/kelunik "kelunik (209 commits)")[![trowski](https://avatars.githubusercontent.com/u/1628287?v=4)](https://github.com/trowski "trowski (175 commits)")[![bwoebi](https://avatars.githubusercontent.com/u/3154871?v=4)](https://github.com/bwoebi "bwoebi (6 commits)")[![sebdesign](https://avatars.githubusercontent.com/u/667144?v=4)](https://github.com/sebdesign "sebdesign (5 commits)")[![ostrolucky](https://avatars.githubusercontent.com/u/496233?v=4)](https://github.com/ostrolucky "ostrolucky (2 commits)")[![Spomky](https://avatars.githubusercontent.com/u/1091072?v=4)](https://github.com/Spomky "Spomky (1 commits)")[![thgs](https://avatars.githubusercontent.com/u/8940963?v=4)](https://github.com/thgs "thgs (1 commits)")[![userqq](https://avatars.githubusercontent.com/u/10743600?v=4)](https://github.com/userqq "userqq (1 commits)")[![villfa](https://avatars.githubusercontent.com/u/2891564?v=4)](https://github.com/villfa "villfa (1 commits)")[![azjezz](https://avatars.githubusercontent.com/u/29315886?v=4)](https://github.com/azjezz "azjezz (1 commits)")[![xtrime-ru](https://avatars.githubusercontent.com/u/34161928?v=4)](https://github.com/xtrime-ru "xtrime-ru (1 commits)")[![danog](https://avatars.githubusercontent.com/u/7339644?v=4)](https://github.com/danog "danog (1 commits)")[![iggyvolz](https://avatars.githubusercontent.com/u/2197376?v=4)](https://github.com/iggyvolz "iggyvolz (1 commits)")[![ivanpepelko](https://avatars.githubusercontent.com/u/7328461?v=4)](https://github.com/ivanpepelko "ivanpepelko (1 commits)")[![Nevay](https://avatars.githubusercontent.com/u/22509671?v=4)](https://github.com/Nevay "Nevay (1 commits)")

---

Tags

amphpasyncionon-blockingphpstreamstreamasyncnon-blockingampamphpio

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/amphp-byte-stream/health.svg)

```
[![Health](https://phpackages.com/badges/amphp-byte-stream/health.svg)](https://phpackages.com/packages/amphp-byte-stream)
```

###  Alternatives

[amphp/redis

Efficient asynchronous communication with Redis servers, enabling scalable and responsive data storage and retrieval.

165634.7k44](/packages/amphp-redis)[amphp/file

Non-blocking access to the filesystem based on Amp and Revolt.

1103.3M94](/packages/amphp-file)[amphp/pipeline

Asynchronous iterators and operators.

7632.7M34](/packages/amphp-pipeline)[amphp/http-server

A non-blocking HTTP application server for PHP based on Amp.

1.3k4.5M81](/packages/amphp-http-server)[amphp/parallel

Parallel processing component for Amp.

85046.2M74](/packages/amphp-parallel)[amphp/dns

Async DNS resolution for Amp.

19339.2M41](/packages/amphp-dns)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
