PHP Function Reference

PHP stream_get_contents() Function



The PHP stream_get_contents() function reads remainder of a stream into a string. This function is 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 maxlength bytes and starting at the specified offset.

Syntax

stream_get_contents(stream, maxlength, offset)

Parameters


Parameters

stream Required. Specify a stream resource, for example returned from fopen() function.
maxlength Optional. Specify the maximum bytes to read. Defaults is -1 (read all the remaining buffer).
offset Optional. Seek to the specified offset before reading. If this number is negative, no seeking will occur and reading will start from the current position. Defaults is -1.

Return Value

Returns a string or false on failure.

Example: reading a file

Lets assume that we have a file called test.txt. This file contains following content:

This is a test file.
It contains dummy content.

In the example below, stream_get_contents() function is used to read the content of it.

<?php
$file = "test.txt";

//open the file in read mode
$stream = fopen($file, 'r');

//reading and displaying the content of the file
echo stream_get_contents($stream);

//closing the stream
fclose($stream);
?>

The output of the above code will be:

This is a test file.
It contains dummy content.

Example: reading a section of a file

By using offset and maxlength parameters, we can specify from where to start reading and maximum length of data to read.

<?php
$file = "test.txt";

//open the file in read mode
$stream = fopen($file, 'r');

//reading and displaying the content of the file
//with maxlength = 20 and offset = 5
echo stream_get_contents($stream, 20, 5);

//closing the stream
fclose($stream);
?>

The output of the above code will be:

is a test file.
It 

❮ PHP Streams Reference