How to append data to a file in PHP

In PHP scripts, there are times when you need to save data. Depending on the type of data and what you may want to do with it later, you can store it in either:

  • a database table
  • a text file
  • any other format of your choice

In this shot, we will learn how to add more data to the content of a text file.

How to append data to a text file in PHP

To append or add more data to a file, you can follow the steps listed below.

Step 1

Identify the file to be written to. For example, you may want to append data to a file named append.txt.

Step 2

Open this file in your script with the fopen() function.

Pass the file’s name and the mode with which you want to open the file as arguments to the fopen() function.

In this case, the mode will be the append mode, indicated by a.

$appendVar = fopen('append.txt','a');

Note: Make sure the correct file path is indicated while writing the file name.

Step 3

Write the new information that you have to add to the file. You can do this using the fwrite() function. For arguments, pass the variable containing the already opened file in append mode and the new set of information to be added.

fwrite($appendVar, 'So this the new line');

We can add more lines using the fwrite() function, as shown above.

Step 4

Close the text file. Use the fclose() function to do this, as shown below.

fclose($appendVar);

You can recheck your text file to see what you have added.

Code

Below is the complete code of the example we have been working through.

<?php
//going to be using append.txt file on my desktop
// opening the file in append mode
$appendVar = fopen('c:/users/systemuser/desktop/append.txt','a');
// writing new lines to the file
$wit = fwrite($appendVar," So this is the new line");
$wit = fwrite($appendVar," That I wish to add");
// Closing the file
if($wit){
echo "it worked";
}
fclose($appendVar);
?>

The fopen() function is also used to create a new file. So, if the file indicated does not exist, the file will be created in the same folder as the script.