Understanding file_get_contents in PHP
file_get_contents is a function in PHP that is used to read the contents of a file into a string. This function is particularly useful when working with text
file_get_contents is a function in PHP that is used to read the contents of a file into a string. This function is particularly useful when working with text files and can be used to retrieve the contents of a file from a remote server or a local file system.
Syntax
The syntax for the file_get_contents function is as follows:
PHP file_get_contents function syntax
file_get_contents(
string $filename,
bool $use_include_path = false,
?resource $context = null,
int $offset = 0,
?int $maxlen = null
): string|false$filename: The path to the file or the URL to be read.$use_include_path: (optional) If set toTRUE, the function will search for the file in the include path.$context: (optional) A valid context resource created withstream_context_create().$offset: (optional) Specifies where to start reading from in the file. If$offsetis negative, the function will start reading from the end of the file.$maxlen: (optional) Specifies the maximum number of bytes to read.
How file_get_contents Works
The file_get_contents() function takes a file path or URL as its first argument and returns the entire contents of the file as a single string. Because it loads everything into memory at once, it is the simplest way to read a whole file — but also the wrong tool for files larger than the available memory.
The return value is the file contents on success, or false on failure. Since an empty file legitimately returns an empty string "" (which is falsy), always compare with the strict !== false operator rather than a loose truthiness check.
Reading a Local File
The most common use is reading a small local file such as a configuration or template file:
$content = file_get_contents('config.txt');
if ($content !== false) {
echo $content;
} else {
echo "Error: could not read the file.";
}file_get_contents() returns false on failure — for example, when the file does not exist or the process lacks read permission — and also emits a PHP warning. To suppress the warning and handle the error yourself, prefix the call with the error-control operator @:
$content = @file_get_contents('missing.txt');
if ($content === false) {
echo "File is unavailable.";
}Reading Part of a File With offset and maxlen
You do not have to read the whole file. The $offset and $maxlen parameters let you read a slice, which is handy for peeking at headers or very large files:
// File contains: "Hello, World!"
// Read 5 bytes starting at offset 7
echo file_get_contents('greeting.txt', false, null, 7, 5); // WorldA common real-world pattern is reading only the first few bytes to detect a file's type, without loading the whole file into memory.
Fetching a Remote URL
When PHP's allow_url_fopen setting is enabled, you can pass an http:// or https:// URL and file_get_contents() will download the response body:
$html = file_get_contents('https://example.com');
if ($html !== false) {
echo substr($html, 0, 100); // first 100 characters
}This is convenient for quick scripts, but for production HTTP calls — where you need timeouts, custom headers, POST bodies, or detailed error codes — the cURL extension is the more robust choice.
Consuming a JSON API
A frequent task is fetching JSON from an API and decoding it into a PHP array. Combine file_get_contents() with json_decode():
$json = file_get_contents('https://api.example.com/data.json');
$data = json_decode($json, true); // true => associative array
echo $data['name'];Sending Headers With a Stream Context
To send custom HTTP headers, set a timeout, or make a POST request, pass a stream context created with stream_context_create() as the third argument:
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => "Content-Type: application/json\r\n",
'content' => json_encode(['key' => 'value']),
'timeout' => 5,
],
]);
$response = file_get_contents('https://api.example.com/submit', false, $context);Benefits
- Simple: retrieves a whole file in a single line, with no need to open, read, and close a handle manually.
- Fast for small files: efficient for reading small to medium configuration, template, or data files.
- Versatile: works on local paths and, with
allow_url_fopen, on remotehttp/https/ftpURLs through the same API.
Limitations and Gotchas
- Memory usage: the whole file is loaded into memory, so reading a multi-gigabyte file can exceed PHP's
memory_limit. Stream large files withfopen()andfread()or read line by line withfgets()instead. - No HTTP error detail: on a remote
404or500, the call returnsfalse(or partial content) without an easy status code. Use the cURL extension when you need to inspect the response status. allow_url_fopenmust be on: remote URLs silently fail if thisphp.inidirective is disabled, which is common on hardened servers.- Empty file vs. failure: an empty file returns
"", notfalse— another reason to test with!== false.
Related Functions
file_put_contents()— the write counterpart; saves a string to a file in one call.file()— reads a file into an array of lines instead of a single string.readfile()— reads a file and writes it straight to the output buffer (good for serving downloads).fopen()— opens a handle for streamed, incremental reading and writing.
Conclusion
file_get_contents() is a simple, versatile function for reading the contents of local files and remote URLs into a string. Its convenience makes it the go-to choice for small files, configuration data, and quick API calls. For very large files, prefer streaming with fopen()/fread(); for production HTTP requests, prefer cURL. Used with a strict !== false check on the return value, it remains one of the most practical I/O functions in PHP.