Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

file_get_contents

Reads a whole file into a string.

Syntax

file_get_contents(string $filename): string|false

Parameters

ParameterTypeDescription
$filenamestringThe path to the file.

Return value

string|falseThe content of the file, or `false` on failure.

Examples

Reading a file:

<?php
 
$file = sys_get_temp_dir() . '/ref-read.txt';
file_put_contents($file, 'Hello, file!');
 
echo file_get_contents($file);

Output:

Hello, file!

Reading and parsing JSON:

<?php
 
$file = sys_get_temp_dir() . '/ref-config.json';
file_put_contents($file, '{"theme": "dark"}');
 
echo json_decode(file_get_contents($file), true)['theme'];

Output:

dark

Notes

If the file is missing, the function raises a warning and returns false. Check file_exists() first. Read large files line by line — the whole file would fill up memory.

See also

Related recipes

In the tutorial

  • Reading and writing files — Working with files in PHP — writing, reading, appending, reading line by line, checking existence and deleting.

Thanks for reading!

Donate to the site — we work hard for you.