Bandwidth throttle at application layer
This library implements traffic shaping on streams (input and output streams).
composer require bandwidth-throttle/bandwidth-throttle
The package is in the namespace
sets the bandwidth limit. E.g. this would set it to 100KiB/s:
throttles a stream. After that any stream operation (e.g.
fread()) will be
limited to the throttle rate.
sets the burst capacity. This is the capacity which can be accumulated while
the stream is not in use. Accumulated capacity can be consumed instantly. Per
default this the amount of bytes for one second from the rate.
sets the initial burst. Per default the throttle starts with 0 accumulated
bytes. Setting an initial burst makes that amount of bytes instantly available.
sets the storage for the underlying token bucket.
The storage determines the scope of the bucket. The default storage is in
the request scope. I.e. it will limit the rate per request. There are
which can be shared amongst requests.
will apply the throttle for both input and output streams. This is the default
will apply the throttle for the input stream only.
will apply the throttle for the output stream only.
removes the throttle from the stream.
This example will stream a video with a rate of 100KiB/s to the browser:
use bandwidthThrottle\BandwidthThrottle; $in = fopen(__DIR__ . "/video.mpg", "r"); $out = fopen("php://output", "w"); $throttle = new BandwidthThrottle(); $throttle->setRate(100, BandwidthThrottle::KIBIBYTES); // Set limit to 100KiB/s $throttle->throttle($out); stream_copy_to_stream($in, $out);
A more sophisticated scenario would be applying multiple throttles on one resource. E.g. the overall bandwidth for the host should be throttled to 1MiB/s and 100KiB/s per request. This will require a shared storage for the 1MiB/s:
use bandwidthThrottle\BandwidthThrottle; use bandwidthThrottle\tokenBucket\storage\FileStorage; $in = fopen(__DIR__ . "/video.mpg", "r"); $out = fopen("php://output", "w"); $hostThrottle = new BandwidthThrottle(); $hostThrottle->setRate(1, BandwidthThrottle::MEBIBYTES); // Set limit to 1MiB/s $hostThrottle->setStorage(new FileStorage(__DIR__ . "/host.throttle")); $hostThrottle->throttle($out); $requestThrottle = new BandwidthThrottle(); $requestThrottle->setRate(100, BandwidthThrottle::KIBIBYTES); // Set limit to 100KiB/s $requestThrottle->throttle($out); stream_copy_to_stream($in, $out);
This project is free and under the WTFPL. Responsible for this project is Markus Malkusch email@example.com.
If you like this project and feel generous donate a few Bitcoins here: 1335STSwu9hST4vcMRppEPgENMHD2r1REK