I've been getting irritated by this bug, and I've tried to fix it but it's been a struggle for me. So I have a php file write to a .txt file, but as I enter different info, it replaces the info that was already in the file, but I don't want it to do that. I want it to add on. Help?
<?php
$filenum = echo rand();
$info = $_GET["info"]; //You have to get the form data
$file = fopen('$filenum.txt', 'w+'); //Open your .txt file
$content = $info. PHP_EOL .$gain. PHP_EOL .$offset;
fwrite($file , $content); //Now lets write it in there
fclose($file ); //Finally close our .txt
die(header("Location: ".$_SERVER["HTTP_REFERER"]));
?>
You're using w+
mode, and the documentation clearly says:
Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
If you want to append, you should use a
or a+
.
BTW, I'm not nor sure why you're using w+
rather than just w
, since you're never reading the file.
Also, you can do it all in one statement using file_put_contents()
$filenum = rand();
$info = $_GET['info'];
$content = $info . PHP_EOL . $gain . PHP_EOL . $offset . PHP_EOL;
file_put_contents("$filenum.txt", $content, FILE_APPEND);
die(header("Location: " . $_SERVER['HTTP_REFERER']));
And notice that you should have PHP_EOL
at the end of $content
. Otherwise, every time you add to the file, it will start on the same line as the last line you added previously.
I don't know the solution but I would recommend you to see the file format you are opening in, I think it should be 'a+' or something like that which opens file for appending rather than 'w+'. I haven't used php much but I think that's the case