PHP File Append

As shown with fopen(), there are multiple ways you can open a file (r, r+, w, etc.).

To append the file means that you preserve its existing contents and add the data to the end of the file. All you need to do to append the file is to open it in either append (a) or read & append (a+) mode as so:

$file=fopen(“myfile.txt”,”a”) or die(“myfile.txt does not exist!”);

Opening the file in append mode will write any data to the end of the file.

If we wanted to actually write some data to the file, we can assign that file a variable and specify what data to append:

$file=fopen(“myfile.txt”,”a”) or die(“myfile.txt does not exist!”);

$info = “I have brown hair.n”;
fwrite($file, $info);
$info = “I have brown eyes.n”;
fwrite($file, $info);
fclose($file);

This bit of code would add two lines to the end of myfile.txt:

I have brown hair.
I have brown eyes.

So, if the original contents of myfile.txt before you opened it were:

I am six feet tall.
I weigh 165lbs.

After appending the new data, your myfile.txt contents would be:

I am six feet tall.
I weigh 165lbs.
I have brown hair.
I have brown eyes.