CodeBlanks Logo Icon CodeBlanks

Writing with file_put_contents()

PHP course · Intermediate · Lesson 71/115

Learn to write a string to a file with file_put_contents().

Writing files with file_put_contents()

To write a string to a file you use the file_put_contents() function. It takes two arguments: the file path and the content to write.

For example, file_put_contents('log.txt', 'Hello'); writes 'Hello' into log.txt. If the file does not exist it is created; if it exists its content is overwritten.

The function returns the number of bytes written. If it returns false, the write failed.

Appending with the FILE_APPEND flag

If you want to add new content to the end of the file instead of overwriting it, pass the FILE_APPEND flag as the third argument.

For example, file_put_contents('log.txt', 'New entry' . PHP_EOL, FILE_APPEND); appends the line 'New entry' to log.txt. The existing content is preserved. PHP_EOL is the end-of-line character (\n on Linux).

This pattern is very useful for log files: each new entry is appended to the end, old entries are kept.

Exercise Write the file and read it back

Use file_put_contents() to write the string 'Entry added' to log.txt. Then read the file with file_get_contents() and print it with echo. Use __DIR__ in the path argument of both functions.

Show example solution
First write file_put_contents(__DIR__ . '/log.txt', 'Entry added'); then echo file_get_contents(__DIR__ . '/log.txt');.
Example solution:
<?php
// Write to the file
file_put_contents(__DIR__ . '/log.txt', 'Entry added');

// Read and print
echo file_get_contents(__DIR__ . '/log.txt');

Test yourself

  1. If file_put_contents('a.txt', 'x') is called and a.txt already exists, what happens?

    • The file is replaced with 'x' (overwritten)
    • 'x' is appended to the end of the file
    • PHP throws an error and leaves the file untouched
    • The content 'xx' is written instead of 'x'
    Show answer

    The file is replaced with 'x' (overwritten) — Correct. file_put_contents() overwrites the file by default; the old content is lost.

  2. Append the entry to the file

    file_put_contents('log.txt', $msg . PHP_EOL, ____);
    Show answer
    file_put_contents('log.txt', $msg . PHP_EOL, FILE_APPEND);
  3. Match file_put_contents concepts

    file_put_contents()
    Writes a string to a file
    First argument
    Is the file path
    Second argument
    Is the content to write
    FILE_APPEND
    Appends to the end

All lessons in Intermediate