This section contains the detail about File Append In PHP.
Until now, we have discussed about how to open, close, read, write & delete file. File write mode is different from file append mode in PHP. Since if we write data to a file(open in the write mode), the previously written data vanished as we open file for writing.
You can write data to existing file without losing data by opening file in append mode. We open file in append mode,the file pointer is placed at the end of the file automatically and writing starts from the end of the previous written data.
Given below the data in the existing file "testFile.txt" :
We are going to add data in this file as follows :
<?php // PHP code to add data to a file(Open in append mode) $myFileName = 'C:\Shared\Ankit K Kaushal\testFile.txt'; $myFileHandle = fopen($myFileName, 'a') or die("cant open file"); $str="File opened in the append mode\n"; fwrite($myFileHandle, $str); $str = "Add data to the exsisting text file\n"; fwrite($myFileHandle, $str); fclose($myFileHandle); ?>
As you can see the code use for writing data is same as we used in previous tutorial to write data. The only difference is that we open the file in the append mode.
File opened in the append mode
Add data to the existing text file