stream_get_contents()

stream_get_contents() — Reads remainder of a stream into a string.

Built-in function of PHP 8.5. The manual lists it as available in PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

What it does

Identical to file_get_contents(), except that stream_get_contents() operates on an already open stream resource and returns the remaining contents in a string, up to length bytes and starting at the specified offset.

Signature

stream_get_contents(resource $stream, ?int $length = null, int $offset = -1): string|false

Parameters

ParameterTypeWhat it takes
$stream (resource)mixedA stream resource (e.g. returned from fopen())
$length (int)mixedThe maximum bytes to read. Defaults to null (read all the remaining buffer).
$offset (int)mixedSeek to the specified offset before reading. If this number is negative, no seeking will occur and reading will start from the current position.

Return value

Returns a string or false on failure.

Example

A runnable snippet:

if ($stream = fopen('http://www.example.com', 'r')) { // print all the page starting at the offset 10 echo stream_get_contents($stream, -1, 10); fclose($stream); } if ($stream = fopen('http://www.example.net', 'r')) { // print the first 5 bytes echo stream_get_contents($stream, 5); fclose($stream); }

Changelog

VersionChange
8.0.0Now throws a ValueError if length is less than -1. Previously, an E_WARNING was raised and false was returned.
8.0.0length is now nullable.

See also

fgets(), fread(), fpassthru()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page stream_get_contents() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.