file_get_contents
Reads a whole file into a string.
Syntax
file_get_contents(string $filename): string|falseParameters
| Parameter | Type | Description |
|---|---|---|
| $filename | string | The 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:
darkNotes
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
- file_put_contents — Writes data to a file.
- file_exists — Checks whether a file or folder exists.
- file — Reads a file into an array of lines.
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.