There are tons of different ways to solve this problem. To be very honest with you, I didn't bother to read the php-code 😉 I'll try to give an explenation of the two "most normal" techniques.. (at least in my world they are)
1)
- Open a new file for writing, put the new entry in it
- Open the old file for reading
- read all data from this file and write it to the first one
- close both files
- delete the old file
- rename the new file to its appropriate name
2)
- Add the new entry to the first index of an array
- Open the old file for reading
- read all the data in it to the same array
- close the file, and reopen for writing
- write each index of the array to file
- close file
example 1:
/ open "new.txt" for writing /
$outfp = fopen("new.txt", "w");
/ open "old.txt" for reading /
$infp = fopen("old.txt", "r");
/ output new entry to "new.txt" /
fputs($outfp, "new entry");
/ concatenate with old data /
while ($oneLine = fgets($infp, 4096))
fputs($outfp, $oneLine);
/ close file pointers /
fclose($infp);
fclose($outfp);
/ remove old file, and rename the new one /
unlink("old.txt");
rename("new.txt", "old.txt");
example 2:
$fileData = array();
$fileData[] = "new entry";
/ open file for reading /
$infp = fopen("old.txt", "r");
/ read old file data to array /
while ($fileData[] = fgets($infp, 4096));
/ close file pointer /
fclose($infp);
/ reopen file for writing /
$outfp = fopen("old.txt", "w");
/ dump array to file /
for ($x = 0; $x < count($fileData); $x++)
fputs($outfp, $fileData[$x]);
/ close file pointer /
fclose($outfp);