Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Files and I/O

PHP file_get_contents() function

Reference for PHP file_get_contents(): read an entire file or stream into a string, offset and length, the false failure value, php://stdin and error handling.

file_get_contents() reads a whole file into a string in one call. It opens the file, reads it and closes it, so there is no handle to manage. For small and medium files it is the shortest and clearest way to read.

It works with any stream wrapper PHP supports, not only local paths: php://stdin, data: URIs and (when enabled) URLs. On failure it emits a warning and returns false, so check the result with === false.

PHP
$text = file_get_contents("notes.txt");
if ($text === false) {
    // could not read
}

Try it

PHP Read a file, or part of it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Handling a missing file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
file_get_contents(
    string $filename,
    bool $use_include_path = false,
    ?resource $context = null,
    int $offset = 0,
    ?int $length = null
): string|false
Name Description
$filename Path or stream URL to read.
$use_include_path If true, also search the directories in include_path. Rarely needed.
$context A stream context (HTTP headers, timeouts); null for none.
$offset Byte position to start reading from. Negative values count from the end for seekable streams.
$length Maximum number of bytes to read; null means to the end.

Return value: the data as a string (an empty string for an empty file), or false on failure.

Errors: an unreadable or missing file raises an E_WARNING; a negative $length throws a ValueError.

Usage notes

  • Compare with === false. An empty file returns "", which is falsy but not an error.
  • The whole file lives in memory. For large files read with fgets() or fread() in chunks instead.
  • Bytes, not characters. $offset and $length count bytes, so they can cut a UTF-8 character in half.
  • Use named arguments to skip the middle parameters: file_get_contents($path, length: 100).
  • Line endings are untouched. Use file() to get an array of lines.
  • Reading URLs needs allow_url_fopen, and fetching user-supplied URLs is a security risk (SSRF). Prefer a proper HTTP client.
  • Paths are relative to the current working directory, not to the script. Build absolute paths with __DIR__ . "/file.txt".
  • The write counterpart is file_put_contents().