In our previous tutorial we have learned how to open, close, read and write to a file. However, the ways which we wrote to a file so far have caused data that was stored in the file to be deleted. So in this lesson we’re going to deal on how to append to a file or to add on to the existing data, but we need to open the file in append mode.
To start with, this application and if we want to add on to a file we need to open it up in append mode. To do this, let’s create first a new file PHP file called “append.php”. And add the following code:
Take note, that when we were to write to a file it would begin writing data at the of the file.
If you open the hello.txt file, you can see that it will look like as shown below.
For appending data, we’re going to use the hello.txt file that we have created in our previous tutorial called “Writing to Files”. At this time we will modify our code above to do the appending of data. And here’s the following code.
You should noticed that the way we write data to the file is exactly the same as in the write lesson. The only thing that is different is that the file pointer is placed at the end of the file in append mode, so all data is added to the end of the file.
After executing the code above, you can notice that the way we write data to the file is exactly the same as in the Writing to File lesson. But the only difference is that the pointer is placed at the end of the file in append mode so all data is added to the end of the file. And the hello.txt file will look like as shown below.
new append data 1
new append data 2