Now, we have learnt about creating, opening, closing, reading and deleting a file. We have opened a file for writing but we have found that the data saved in the file is erased. Now, we will use the command append and will try to write in the presence of existing data.
File Open and Append in PHP
In order to write text in a file without erasing the data, we have to use append command. Here is code for that;
Code of PHP
$fh = fopen($mynewFile, 'a');
With the use of append command, the pointer will come to the last part of the data for writing new text.
File Write and Appending the data in PHP
Here, we explain you about the use append command in the file newfile.txt for writing new data.
Code of PHP
$fh = fopen($mynewFile, 'a') or die("file can not open");
$stringData = "Recent Addition one\n";
$stringData = "Recent Addition two\n";
It has been seen that the way of adding text in a file is similar to the way of writing new data. The difference is created due to the changed position of the pointer. By using append command; the pointer comes to the ending of the text. So the data of newfile.text can be look like;
Stuffing of the file newfile.txt
Recent Addition one
Recent Addition two
Why we use Append command in PHP
We can not guess the importance of this command by this example. But it is true that this command is very helpful in daily use. Mostly, web servers contain some or the other kind of log. In these logs, information about different things is stored like viewers, faults and the installed files.
The use of log is mostly for the files events which get happen for an episode of time. It has been seen that logs are very useful for appending in a file.