Reading and writing files

A file is the second place where a PHP program keeps data, after its variables. This lesson reads one, writes one, checks one before reading it, and names it in a way that survives a move.

file_get_contents

Function file_get_contents reads a whole file into a string.

Build the path from __DIR__ so the script works from any working directory. Use it for small text files and templates.

The file data.txt:

Hello files

The script that reads it, read.php:

<?php $path = __DIR__ . "/data.txt"; $text = file_get_contents($path); echo $text;

php read.php

Hello files

The whole file arrives as one string, including the line break at its end, which is why the output ends with a new line. A larger file would still be one string, and the whole of it would sit in memory.

file_put_contents with LOCK_EX

Function file_put_contents writes a string in one call. Add flag LOCK_EX to lock the file during writing.

The function returns the number of bytes written or false on failure.

<?php $path = __DIR__ . "/data.txt"; $written = file_put_contents($path, "Hello files\n", LOCK_EX); var_dump($written); echo file_get_contents($path);

php write.php

int(12)
Hello files

Twelve bytes went to the file, which the second line reads back. The lock keeps a second writer out for the moment of the write, so two requests cannot leave half a line each.

Check with is_file

Always check existence before reading user supplied paths.

Function is_file returns true only for regular files. Function file_exists also matches directories, so pick the check that fits the task.

<?php $path = __DIR__ . "/data.txt"; file_put_contents($path, "Hello files\n", LOCK_EX); var_dump(is_file($path)); var_dump(file_exists($path)); var_dump(is_file(__DIR__)); var_dump(file_exists(__DIR__));

php exists.php

bool(true)
bool(true)
bool(false)
bool(true)

Both checks agree on the file, and they disagree on the folder: __DIR__ is a directory, so it is no file but it does exist. A read of a path that failed is_file is a mistake worth catching before the function tries.

Anchor paths with __DIR__

Constant __DIR__ holds the directory of the current file. Join it with a file name to get an absolute path.

Absolute paths keep includes and reads stable after moves and deploys.

<?php $path = __DIR__ . "/data.txt"; file_put_contents($path, "Hello files\n", LOCK_EX); var_dump(dirname($path) === __DIR__); var_dump(is_file($path));

php dir.php

bool(true)
bool(true)

dirname() of the joined path gives __DIR__ back, so the name of the folder travels with the file; the second line shows that the path reaches a real file from whatever folder the command was started in.

Exercises

  1. Write two lines into data.txt with file_put_contents and read them back. How many bytes does the write report?
  2. Add a third argument FILE_APPEND to the write and run it twice. What does the file hold after the second run?
  3. Check __DIR__ . "/missing.txt" with both functions. Which values do the two return?
  4. Print basename($path) and dirname($path) for the data file. Which part is the folder, and which is the name?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does file_get_contents() return?

    Answer

    The whole file as one string

    The function reads the file into a string, line breaks included, which suits small files.

  2. What does the LOCK_EX flag of file_put_contents() add?

    Answer

    It keeps another writer out during the write

    The exclusive lock protects the moment of the write, so two requests do not interleave their bytes.

  3. What is the difference between is_file() and file_exists()?

    Answer

    is_file() is true only for regular files, file_exists() is also true for folders

    A directory exists but is not a regular file, which is exactly the difference the example shows.

  4. Why is __DIR__ . "/data.txt" better than "data.txt"?

    Answer

    It names the file next to the script, whatever folder the program runs from

    A bare name depends on the working directory; __DIR__ fixes the folder of the current file.

  5. What does this program print? <?php $path = __DIR__ . "/x.txt"; var_dump(file_put_contents($path, "abc"));

    Answer

    int(3)

    The function returns the number of bytes written, and three letters are three bytes.

  6. What does this program print? <?php $path = __DIR__ . "/x.txt"; file_put_contents($path, "abc"); echo file_get_contents($path);

    Answer

    abc

    The write creates the file, and the read returns the three letters it holds.

  7. What does this program print? <?php var_dump(is_file(__DIR__));

    Answer

    bool(false)

    __DIR__ is a directory, and is_file is true only for regular files.

  8. What does this program print? <?php var_dump(file_exists(__DIR__));

    Answer

    bool(true)

    The folder does exist, and file_exists answers for folders as well as files.

  9. What does this program print? <?php echo dirname("/var/www/app/data.txt");

    Answer

    /var/www/app

    dirname returns the folder part of the path and drops the last name.

  10. What does file_put_contents($path, "abcd") return when it succeeds?

    Answer

    The number of bytes written, here 4

    The function returns the byte count and only gives false when the write failed.

The code on this page was run with PHP 8.5.13 (php -v) in Alpine Linux, with the commands shown above.

Article author: Arthur Isaev