user2957574 user2957574 - 4 months ago 14
HTML Question

How can I keep previous data in a text file?

So basically, I have a form that opens a php file when submitted, i have the php writing to a file, but it will not continue adding values, the text file only has one "1" inside of it when it is supposed to have a "1" inside for every time the form has been submitted. Here is my code.

<?php
$myFile = "Data.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "1";
fwrite($fh, $stringData);
fclose($fh);
?>


Any ideas?

Answer

Either open in append only format as Robert Rozas stated: fopen($myFile, 'a+');

Or get the contents and do the append manually some pseudo[esk]-code:

$contents = file_get_contents("somefile.txt");
//generate what to write
$contents .= $whatIGenerated;
$success = file_put_contents("somefile.txt", $contents);