CodeBlanks Logo Icon CodeBlanks

Reading with file_get_contents()

PHP course · Intermediate · Lesson 70/115

Learn to read a file's full content as a string with file_get_contents().

Reading files with file_get_contents()

In PHP you use file_get_contents() to read a file's entire content at once as a string. The function takes the file path as its argument and returns the content.

For example, $content = file_get_contents('note.txt'); reads note.txt and stores its content in the $content variable. You can then echo the string, split it or pass it to another function.

If the file cannot be found the function returns false. That is why in production code it is a good habit to check the returned value.

File paths and __DIR__

file_get_contents() accepts a relative or absolute file path. In production code the __DIR__ magic constant is very handy to anchor paths to the script's own folder.

For example, file_get_contents(__DIR__ . '/settings.txt') reads settings.txt from the same folder as the PHP file that calls it. This keeps the path correct even if the script is invoked from different working directories.

Note the '/' separator between the directory and the file name. PHP accepts / on both Linux and Windows.

Exercise Read the file and print it

First use file_put_contents() to write 'Hello PHP' into note.txt (given part). Then read the file with file_get_contents() using __DIR__, store the content in $content and print it with echo.

Show example solution
Assign file_get_contents(__DIR__ . '/note.txt') to $content, then echo $content; to print it.
Example solution:
<?php
// Write sample content into the file
file_put_contents(__DIR__ . '/note.txt', 'Hello PHP');

// Read the file
$content = file_get_contents(__DIR__ . '/note.txt');

// Print it
echo $content;

Test yourself

  1. What does file_get_contents('data.txt') return on success?

    • A file handle (resource)
    • The file's content as a string
    • The number of bytes read as an integer
    • Nothing, it is void
    Show answer

    The file's content as a string — Correct. file_get_contents() returns the whole file content as a single string.

  2. Read the file as a string

    $content = ____(__DIR__ . '/note.txt');
    Show answer
    $content = file_get_contents(__DIR__ . '/note.txt');
  3. Match file_get_contents concepts

    file_get_contents()
    Reads whole file as a string
    File path
    Is the first argument
    __DIR__
    Gives the script's directory
    false
    Returned when the file is missing

All lessons in Intermediate