File Append

☰ Menu Content


If you want to append to a file, that is, add on to the existing data, then you need to open the file in append mode.

File Open: Append

If we want to add on to a file we need to open it up in append "a" mode.

The code below does just that.

PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myfile, 'a');

If we were to write to the file it would begin writing data at the end of the file.

File Write: Appending Data

Study the example shown below:-

PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'a') or die("can't open file");

$stringData = "New Stuff 1\n";
fwrite($fh, $stringData);

$stringData = "New Stuff 2\n";
fwrite($fh, $stringData);
fclose($fh);

The contents of the file testFile.txt would now look like this:
Contents of the testFile.txt File:
Floppy Jalopy
Pointy Pinto
New Stuff 1
New Stuff 2

Append: Why Use It

Appending data onto a file is actually used everyday.

For example nearly all web servers have a log of some sort.

These various logs keep track of all kinds of information, such as: errors, visitors, and even files that are installed on the machine.

A log is basically used to document events that occur over a period of time, rather than all at once. Logs file is a perfect use for append.

Note
For more detail please see Php Manual at http://www.php.net

Php Tutorial Content (menu)