PHP file_get_contents() Function

Quick summary: The PHP file_get_contents() function reads the entire file or URL into a string.

PHP file_get_contents() Syntax

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

PHP file_get_contents() Basic examples

$content = file_get_contents('example.txt');
var_dump($content);
PHP
Output:
string(...) "File contents"

Reads a file into a string.

PHP file_get_contents() Real-world usage

$json = file_get_contents('https://api.example.com/data');
PHP
Output:
string(...) "{...}"

Fetches API responses.

PHP file_get_contents() Edge cases

var_dump(file_get_contents('missing.txt'));
PHP
Output:
bool(false)

Returns false if the file cannot be read.

PHP file_get_contents() Common mistakes

Ignoring read failures

file_get_contents can fail silently.

Incorrect
file_get_contents('file.txt');
Correct
$data = file_get_contents('file.txt'); if ($data === false) { /* handle error */ }

Always check the return value.

PHP file_get_contents() Frequently Asked Questions

What does file_get_contents() do?

Reads a file or URL into a string.

Can it fetch remote URLs?

Yes, if allow_url_fopen is enabled.

What happens if file not found?

Returns false.

Use case?

Reading files or API responses.

Does it modify file?

No.

Performance?

Fast for small files.

Can read large files?

Not memory efficient.

Alternative?

fopen + fread.

Supports streams?

Yes.

Common mistake?

Ignoring errors.

Can set context?

Yes.

Safe for APIs?

Yes.

PHP file_get_contents() Related PHP Functions