Backend Development 3 min read

PHP file_get_contents Function: Description, Parameters, Return Value, and Usage Examples

This article explains the PHP file_get_contents function, detailing its purpose of reading an entire file into a string, describing each parameter and return value, and providing multiple practical code examples demonstrating basic usage, include path handling, partial reads, and custom stream contexts.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP file_get_contents Function: Description, Parameters, Return Value, and Usage Examples

The file_get_contents() function reads an entire file into a string and is the preferred method for file content retrieval in PHP, optionally using memory‑mapped I/O for better performance.

Parameters :

filename : the path to the file to read.

use_include_path : (bool) whether to search the include_path (available since PHP 5).

context : a stream context resource; use NULL if not needed.

offset : the starting position for reading (not supported for remote files).

maxlen : the maximum number of bytes to read; defaults to reading until EOF.

Return value : on success, the function returns the file’s contents as a string; on failure it returns FALSE .

Examples :

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

Read a local file using the include path flag (PHP 5 and later):

<?php
// PHP 5 and later
$file = file_get_contents('./people.txt', FILE_USE_INCLUDE_PATH);
?>

Read a specific portion of a file (starting at byte 20, reading 14 bytes):

<?php
$section = file_get_contents('./people.txt', NULL, NULL, 20, 14);
var_dump($section);
?>

Use a custom stream context to set HTTP headers before fetching a remote file:

<?php
$opts = array(
    'http' => array(
        'method'  => "GET",
        'header'  => "Accept-language: en\r\n".
                    "Cookie: foo=bar\r\n"
    )
);
$context = stream_context_create($opts);
$file = file_get_contents('http://www.example.com/', false, $context);
?>
Backend Developmentfile handlingfile_get_contentsstream context
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.