PHP - File Open: Append
If we want to add on to a file we need to open it up in append 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.
PHP - File Write: Appending Data
Using the testFile.txt file we created in the File Write lesson , we are going to append on some more data.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, a) or die("cant open file");
$stringData = "New Stuff 1 ";
fwrite($fh, $stringData);
$stringData = "New Stuff 2 ";
fwrite($fh, $stringData);
fclose($fh);
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.
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
PHP - Append: Why Use It?
The above example may not seem very useful, but appending data onto a file is actually used everyday. Almost 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: a perfect use for append!