250 of 410 menu

The file_get_contents Function

The file_get_contents function reads the contents of a file and returns it as a string. The first parameter is the path to the file, the second - is a flag to enable the search path, the third - is the stream context, the fourth - is the offset to start reading from, the fifth - is the maximum data length.

The third parameter is especially useful when you need to search for files in the standard directories specified in the PHP configuration, and not only by the absolute path.

Syntax

file_get_contents( string $filename, bool $use_include_path = false, ?resource $context = null, int $offset = 0, ?int $maxlen = null ): string|false

Parameters

Parameter Description
filename Path to the file or URL
use_include_path If set to true, the function will search for the file in the directories specified in the include_path parameter in the PHP settings in the php.ini file. By default false.
context Stream context resource
offset Offset to start reading from
maxlen Maximum length of data to read

Example

Reading the contents of a local file:

<?php $res = file_get_contents('data.txt'); echo $res; ?>

Code execution result:

'abcde'

Example

Reading part of a file with offset and length specified:

<?php $res = file_get_contents('data.txt', false, null, 1, 3); echo $res; ?>

Code execution result:

'bcd'

Example

Reading the contents of a web page:

<?php $res = file_get_contents('https://example.com'); echo substr($res, 0, 50) . '...'; ?>

Code execution result:

'<!doctype html><html><head><title>Example D...'

Example

Searching for a file in the include_path:

<?php $res = file_get_contents('config.ini', true); echo $res; ?>

Code execution result:

'config_data'

Stream Context Parameter

The context parameter allows you to pass a stream context resource, which can modify the function's behavior when working with files or network resources.

A context resource created by the stream_context_create function. If no special settings are required, you can pass null.

Context capabilities:

  • Setting HTTP headers for requests
  • Configuring connection timeouts
  • Specifying a proxy server
  • Working with SSL/TLS parameters
  • Configuring filesystem access

Work example:

<?php $opts = [ 'http' => [ 'method' => "GET", 'header' => "Accept-language: en\r\n" ] ]; $context = stream_context_create($opts); $res = file_get_contents('https://example.com', false, $context); ?>

See Also

  • the file_put_contents function,
    which writes data to a file
  • the fopen function,
    which opens a file
  • the file function,
    which reads a file into an array of strings
byenru