๐ŸŽ“ A1Learner
๐Ÿ”
0 of 38 lessons completed

Writing Files

Writing files is the act of saving text into a file on disk. The file_put_contents function writes a whole string to a file in one call.

Write two lines and read them back

file_put_contents saves the text to the file note.txt. file_get_contents reads the file back so echo can print the saved text, and the next lesson reads files in depth.

<?php
file_put_contents("note.txt", "First line\nSecond line\n");
echo file_get_contents("note.txt");

FILE_APPEND adds a third line

The first write saves two lines. The second write passes FILE_APPEND, so its line lands after the old lines instead of replacing them.

<?php
file_put_contents("list.txt", "One\nTwo\n");
file_put_contents("list.txt", "Three\n", FILE_APPEND);
echo file_get_contents("list.txt");

A counter file rises by one

The setup line saves the text 5 in the counter file. The program reads that text back, casts it to a number, adds one and writes the new value back.

<?php
file_put_contents("count.txt", "5");
$count = (int) file_get_contents("count.txt");
$count = $count + 1;
file_put_contents("count.txt", (string) $count);
echo file_get_contents("count.txt"), "\n";

Example

<?php
file_put_contents("guest.txt", "Hana visited\n");
file_put_contents("guest.txt", "Mina visited\n", FILE_APPEND);
echo file_get_contents("guest.txt");

Key points

  • file_put_contents saves text to the file named in its first argument.
  • The text in the second argument becomes the whole content of the file.
  • A write to a new name creates that file.
  • FILE_APPEND adds new text after the old content instead of replacing it.
  • file_get_contents reads a whole file back as one string.

In this example, the first write creates the guest log with one entry. The second write passes FILE_APPEND, so the second entry lands after the first one. The read back prints both entries in order.

Note

The next lesson reads files in depth.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does the FILE_APPEND flag do in a file_put_contents call?