14 – PHP File Handling: File Append

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 the file can't be open..and it can prevent some error might happen

echo'Could not open the file';

}

?>

If you open the hello.txt file, you can see that it will look like as shown below.

hello
World

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.

//if the file can't be open..and it can prevent some error might happen

echo'Could not open the file';

}

?>

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.

Hello Itsourcecoders, welcome to itsourcecode.com. I'm Joken Villanueva, MIT a passionate Blogger, Programmer and a Hobbyist. I started Itsourcecode because I wanted to give back and Share all the learnings and knowledge I've learned in my career and I believe through this website I would be able to help and assist those newbie programmers in enhancing their skills from different programming languages. So let us all help each other by sharing our ideas!