file_get_contents

Reads an entire file into a string in one call, with optional offset and length.

Signature
file_get_contents(string $filename, bool $use_include_path = false, ?resource $context = null, int $offset = 0, ?int $length = null): string|false
  • Added in PHP 4.3.0

Parameters

ParameterTypeDescription
$filenamestringPath to the file to read.
$use_include_pathoptionalbool= falseSearch the include_path for the file as well as the given path.
$contextoptional?resource= nullA stream context from stream_context_create(), or null for none.
$offsetoptionalint= 0Byte offset to start reading from. Negative values count back from the end of the stream.
$lengthoptional?int= nullMaximum number of bytes to read. null reads to end of file.

Return value

string|falseThe file contents as a string, or false on failure.

Errors

Emits an E_WARNING and returns false if the file cannot be opened; throws a ValueError if filename contains a null byte or if length is negative.

Changelog

  • PHP 8.0.0length is nullable now.
  • PHP 7.1.0Support for negative offset values was added.

file_get_contents is the shortest path from a filename to a string. It opens the file, reads it, closes it, and hands you the bytes — no handle to manage and no loop to write. For configuration files, templates, JSON payloads and anything else that comfortably fits in memory, it is the right default.

When to reach for it

  • You want the whole file and you want it now.
  • The file is small enough that holding it in RAM is fine.
  • You do not need to write back to the same handle.

What trips people up

The return type is string|false, and an empty file returns "" — which is falsy. Never test the result with if (!$data); compare against false with ===.

Memory is the other trap. Reading a 2 GB log allocates 2 GB. If the file might be large, either pass $length to cap the read or switch to fopen plus fgets and stream it line by line.

Finally, a missing file raises an E_WARNING, not an exception. Guard with is_readable() first, or silence it with @ only when you check the return value immediately after.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Load a JSON config file and pass it straight to json_decode.
  • Read an HTML email template before running str_replace on its placeholders.
  • Grab the last 4 KB of a log file using a negative offset, without reading the whole thing.

Frequently asked questions

What is the difference between file_get_contents and file?

`file_get_contents` returns the entire file as one string, while `file()` returns an array with one element per line. Use `file()` when you want to iterate lines and `file_get_contents` when you want the raw bytes.

Why does file_get_contents return false?

Because the file does not exist, is not readable, or the path is wrong — PHP also emits an E_WARNING with the reason. Check `is_readable($path)` and remember that relative paths resolve against the current working directory, not the script's directory.

Is file_get_contents faster than fopen and fread?

For reading a whole file, yes — it is a single optimized call with no PHP-level loop. For very large files `fopen` plus a read loop is better because it keeps memory usage flat.

More examples

Checking for failure correctly

The file read succeeded, so `$data === false` is false. But `empty($data)` is true, which is why the falsy check is the classic source of "my file won't load" bug reports on perfectly valid empty files.

Example · php
<?php
file_put_contents('empty.txt', '');

$data = file_get_contents('empty.txt');

var_dump($data === false);   // real failure?
var_dump(empty($data));      // misleading truthiness check
echo "length: ", strlen($data), "\n";

unlink('empty.txt');

Reading a JSON config file

The output shows `retries: 3` and `debug: true`. This is the standard config-loading pattern: read to string, decode, and check the read result against `false` before decoding.

Example · php
<?php
file_put_contents('config.json', '{"debug":true,"retries":3}');

$raw = file_get_contents('config.json');
if ($raw === false) {
    exit("could not read config\n");
}

$config = json_decode($raw, true);
echo "retries: ", $config['retries'], "\n";
echo "debug: ", var_export($config['debug'], true), "\n";

unlink('config.json');

Capping the read on a large file

`filesize()` reports 5500 bytes but only 40 were loaded into memory. Passing `$length` is the cheap way to peek at a file's header without allocating the whole thing.

Example · php
<?php
file_put_contents('big.log', str_repeat("noise line\n", 500));

// Only pull the first 40 bytes instead of all 5500
$head = file_get_contents('big.log', false, null, 0, 40);

echo "file size: ", filesize('big.log'), "\n";
echo "read: ", strlen($head), " bytes\n";
echo $head, "\n";

unlink('big.log');

Discussion

  • Be the first to comment on this lesson.