PHP file_get_contents() Function

Usage — The PHP file_get_contents() function is used to read an entire file into a string. If you use it to read remote files, make sure that any URL with special characters like spaces is properly encoded using the urlencode() function in PHP.

It has the following syntax:

PHP

string file_get_contents ( string $filename [, bool $use_include_path = false [, resource $context [, int $offset = 0 [, int $maxlen ]]]] )

Here is an example of using file_get_contents():

PHP

// Output — John, Sally, Peter, Amanda
echo file_get_contents("names.txt");

Return Value — This function returns the read data on success or FALSE on failure. You should keep in mind that file_get_contents() may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE.

Additional Information — I would like to say that this function should be your preferred way to read the contents of a file into a string because it will use memory mapping techniques, if this is supported by the server, to enhance performance.

One major difference between file() and file_get_contents() is that that file_get_contents() reads the content in a string , starting at the specified offset up to maxlen bytes while file() reads the content in an array.

Remember that if you’re opening a URI with special characters, such as spaces, you need to encode the URI with urlencode() for the function to work properly.

PHP Version and Changelog — The file_get_contents() function is available in PHP 4 >= 4.3.0, PHP 5, PHP 7. The offset parameter was added in PHP 5.1. The maxlen parameter was also added in PHP 5.1.

Relevant Functions — Other related PHP functions that you should know about are: file() which reads entire file into an array, fgets() which gets line from file pointer, fread() which does a binary-safe file read, readfile() which outputs a file, file_put_contents() which write a string to a file, stream_get_contents() which reads remainder of a stream into a string and stream_context_create() which creates a stream context.

Go Directly To — usage, parameters, working examples or additional tips.

Parameters

filename

The filename parameter is used to specify name of the file to read. This is a required parameter.

use_include_path

The use_include_path parameter is used to specify if the FILE_USE_INCLUDE_PATH constant (in php.ini) can be used to trigger include path search. This is an optional parameter.

context

The context parameter is used to specify a valid context resource created with stream_context_create(). If you don’t need to use a custom context, you can skip this parameter by NULL. This is an optional parameter.

offset

The offset parameter is used to specify the offset where the reading starts on the original stream. Negative offsets will result in counting from the end of the stream. This is an optional parameter.

Remember that seeking (offset) is not supported with remote files. Attempting to seek on non-local files may work with small offsets, but this is unpredictable because it works on the buffered stream.

maxlen

The maxlen parameter is used to specify the maximum length of data to be read. The default is to read until end of file is reached. This is an optional parameter.

Working Examples

Here are some examples of using the file_get_contents() function:

PHP

$homepage = file_get_contents('http://www.example.com/');
echo $homepage;

The above code will get and output the source of the homepage of given website. Similarly, the following example shows how to read a section of a file.

PHP

// Read 14 characters starting from the 21st character
$section = file_get_contents('story.txt', NULL, NULL, 20, 14);
var_dump($section);

The following example shows how to use stream contexts to open a remote file.

PHP

$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: visitor=EGFE129F\r\n"
  )
);

$context = stream_context_create($opts);
$file = file_get_contents('http://www.example.com/', false, $context);

Additional Tips

Here are some of the most upvoted tips taken from the comment section of the PHP manual:

  1. I would like to mention that file_get_contents() can do a POST. You need to create a context for that first:

    PHP

    $opts = array('http' =>
        array(
            'method'  => 'POST',
            'header'  => "Content-Type: text/xml\r\n".
                               "Authorization: Basic ".base64_encode("$https_user:$https_password")."\r\n",
            'content' => $body,
            'timeout' => 60
        )
    );
    
    $context  = stream_context_create($opts);
    $url = 'https://'.$https_server;
    $result = file_get_contents($url, false, $context, -1, 40000);

    Suggested by - Bart Friederichs

  2. You can use a streaming context to set the timeout properly without messing with ini values:

    PHP

    $ctx = stream_context_create(array(
        'http' => array(
            'timeout' => 1
        ))
    );
    
    file_get_contents("http://example.com/", 0, $ctx);
    

    Suggested by - joachimb at gmail dot com

  3. A UTF-8 issue I’ve encountered is that of reading a URL with a non-UTF-8 encoding that is later displayed improperly since file_get_contents() related to it as UTF-8. This small function should show you how to address this issue:

    PHP

    function file_get_contents_utf8($fn) {
        $content = file_get_contents($fn);
        return mb_convert_encoding($content, 'UTF-8',
          mb_detect_encoding($content, 'UTF-8, ISO-8859-1', true));
    }
    

    Suggested by - colnector bla-at_bla colnect.com

  4. Seems file looks for the file inside the current working (executing) directory before looking in the include path, even with the FILE_USE_INCLUDE_PATH flag specified.

    By the way I feel the doc is not entirely clear on the exact order of inclusion (see include). It seems to say the include_path is the first location to be searched, but I have come across at least one case where the directory containing the file including was actually the first to be searched.

    Suggested by - francois hill

Further Reading

  1. You can read more about the PHP file_get_contents() function on PHP.net.

Reader Comments

1. You can register or login to post a comment. Asking readers to register improves the quality of discussion.

2. As a registered user, you will also get to access features like choosing between a light and dark theme or anything else that we might implement in future.

Follow Us For Updates

FacebookTwitterGoogle+
Go To Top