PHP Function Reference

PHP file_get_contents() Function



The PHP file_get_contents() function reads a file into a string.

This function is similar to file(), except that file_get_contents() returns the file in a string, starting at the specified offset up to the specified length bytes. On failure, file_get_contents() returns false.

This function is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by the server, to enhance performance.

Syntax

file_get_contents(filename, use_include_path,
                  context, offset, length)

Parameters

filename Required. Specify the path to the file to read.
use_include_path Optional. Set to '1' or true if you want to search for the file in the include_path, too. include_path can be set in php.ini.
context Optional. Specify a valid context resource created with stream_context_create() function. Context is a set of options that can modify the behavior of a stream. Can be skipped by using null.
offset Optional. Specify the offset where the reading starts on the original stream. Negative offsets count from the end of the stream. Seeking (offset) is not supported with remote files.
length Optional. Specify the maximum length of data to read. The default is to read until end of file is reached.

Return Value

Returns the read data or false on failure.

Note: This function may return Boolean false, but may also return a non-Boolean value which evaluates to false. Therefore, use === operator for testing the return value of this function.

Exceptions

Generates an E_WARNING level error if filename is not found, length is less than zero, or if seeking to the specified offset in the stream fails. When this function is called on a directory, an E_WARNING level error is generated on Windows, and as of PHP 7.4 on other operating systems as well.

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, file_get_contents() function is used to read the content of it.

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

//reading the content of the file
//and displaying it
echo file_get_contents($file)."\n";
?>

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 length parameters, we can specify from where to start reading and maximum length of data to read.

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

//using offset and length parameters
echo file_get_contents($file, false, null, 21, 18);
?>

The output of the above code will be:

It contains dummy

❮ PHP Filesystem Reference