-
Notifications
You must be signed in to change notification settings - Fork 6
Examples
Ben Ramsey edited this page Mar 2, 2025
·
2 revisions
ramsey/http-range is designed to be used with PSR-7 RequestInterface
objects. Assuming that $request in the following example conforms to this
interface, the following example shows how to use this library to parse an HTTP
Range header.
The following HTTP request uses a Range header to request the first 500 bytes
of the resource at /image/1234.
GET /image/1234 HTTP/1.1
Host: example.com
Range: bytes=0-499When receiving a request like this, you can parse the Range header using the
following.
use Ramsey\Http\Range\Exception\NoRangeException;
use Ramsey\Http\Range\Range;
$filePath = '/path/to/image/1234.jpg';
$filePieces = [];
$range = new Range($request, filesize($filePath));
try {
// getRanges() always returns an iterable collection of range values,
// even if there is only one range, as is the case in this example.
foreach ($range->getUnit()->getRanges() as $rangeValue) {
$filePieces[] = file_get_contents(
filename: $filePath,
offset: $rangeValue->getStart(),
length: $rangeValue->getLength(),
);
}
} catch (NoRangeException $e) {
// This wasn't a range request or the `Range` header was empty.
}