Reputation: 692
I saw this question and I wanted to ask a question in the comment but didn't have enough reputation. So I'm asking the question here.
I have a form in HTML:
<form action="myprocessingscript.php" method="POST">
Name : <input name="field1" type="text" />
Email : <input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
And a processing script in php, myprocessingscript.php
:
if (isset($_POST['field1']) && isset($_POST['field2'])) {
$data = 'comments.txt' . $_POST['field1'] . ' ' . $_POST['field2'] . "\n";
$ret = file_put_contents('comments.txt', $data);
if ($ret === false) {
die('There was an error Sending The Comment');
}
else {
echo "The Comment Has Been Sent Succesfully !";
}
}
else {
die('Fill in The Form Please !');
}
if (isset($_POST['field1']) && isset($_POST['field2'])) {
$data = 'comments.txt' . $_POST['field1'] . ' ' . $_POST['field2'] . "\n";
$ret = file_put_contents('comments.txt', $data);
if ($ret === false) {
die('There was an error Sending The Comment');
}
else {
echo "The Comment Has Been Sent Succesfully !";
}
}
else {
die('no post data to process');
}
When I write something in the form to a text file (comments.txt) the previous text is deleted - what should I do?
Upvotes: 2
Views: 1218
Reputation: 8472
You just need to add the 'append' flag to file_put_contents()
:
file_put_contents('comments.txt', $data, FILE_APPEND);
See : https://www.php.net/manual/en/function.file-put-contents.php
Upvotes: 5