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.
  1. <?php
  2. //specify the filename and we call it as hello.txt
  3. $testfile = 'hello.txt';
  4. //and inside the if statement, we pass the $testfile variable to fopen and we specify the mode as write
  5. //and fopen return a handle as a value, and using handle is useful because we could close it
  6. if($fh = fopen($testfile, 'a')){// we are in append mode
  7.  
  8. }else{
  9. //if the file can't be open..and it can prevent some error might happen
  10. echo 'Could not open the file';
  11. }
  12.  
  13. ?>
If you open the hello.txt file, you can see that it will look like as shown below.

Contents of hello.txt

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.
  1. <?php
  2. //specify the filename and we call it as hello.txt
  3. $testfile = 'hello.txt';
  4. //and inside the if statement, we pass the $testfile variable to fopen and we specify the mode as write
  5. //and fopen return a handle as a value, and using handle is useful because we could close it
  6. if($fh = fopen($testfile, 'a')){// we are in append mode
  7. $somestring = "\nnew append data 1\n";
  8. fwrite($fh, $somestring);
  9. $somestring = "new append data 2\n";
  10. fwrite($fh, $somestring);
  11. //close the handle
  12. fclose($fh);
  13. }else{
  14. //if the file can't be open..and it can prevent some error might happen
  15. echo 'Could not open the file';
  16. }
  17. ?>
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.

Contents of hello.txt

hello World new append data 1 new append data 2

Add new comment