Lesson 16: Writing to a text file

In the previous lesson, we learned to read from a text file. In this lesson, we will learn to write to a text file.

The two methods are very similar, but there is one very important difference: You must have write permissions to the file. This means that the file will have to be located in a folder where you have the necessary permissions.

If you work locally on your own computer, you can set the permissions yourself: right-click on the folder and choose "Properties". With most web hosts, you will normally have one folder with write permissions. It's often called something like "cgi-bin", "log", "databases" or something similar. If your web host permits it, you might also be able to set permissions yourself. Usually you can simply right-click on a folder in your FTP client and choose "properties" or "permissions" or something similar. The screendumps below shows how it's done in FileZilla.

Read more on your web host's support pages.

Note that it is the text file that needs to be in the folder with write permissions - not the PHP file.

Open the text file for writing

In the same way as when reading from a text file, the fopen function is used for writing, but this time we set the mode to "w" (writing) or "a" (appending).

The difference between writing and appending is where the 'cursor' is located - either at the beginning or at the end of the text file.

The examples in this lesson use an empty text file called textfile.txt. But you can also create your own text file if you like.

First, let us try to open the text file for writing:

<?php// Open the text file$f = fopen("textfile.txt", "w");// Close the text filefclose($f);?>

Since we opened the file for writing, the line is added at the top, and thus overwrites the existing line. If we instead open the file appending, the line is added at the bottom of the text file, which then will increase by one line each time it's written to.

Example 2: Adding a text block to a text file

Of course, it is also possible to add an entire text block, instead of just a single line, like this: