Reputation: 397
Basically, I just want to add a line to a text file, but when I do it it deletes the previous content of the file.
How can I add a line to a text file without deleting the previous content?
<?php
$template = $_POST["template"];
$templateFile = fopen("templates.txt", "a");
file_put_contents("templates.txt", $template);
fclose($templateFile);
//header function to go back to my original page where the form was
?>
Upvotes: 1
Views: 327
Reputation: 1895
You are mixing c style fopen
fwrite
and fclose
with PHP specific file_put_contents
function.
You have to choose one.
Using the first method you have to fopen
the file, specifying name, and mode, writing on the file using fwrite
, and closing the file with fclose
.
Alternatively you can use the PHP file_put_contents
(implementation, documentation), and as you can see the function itself checks that the file is a regular file, that is not locked by another application, writes the content, and close the file.
TL;DR To append to a file in PHP use the following code:
file_put_contents("myfile.txt", "content", FILE_APPEND);
Remember that writing postdata to a file is not secure!
Upvotes: 1
Reputation: 59701
You don't need to open the file with fopen()
if you use file_put_contents()
, it already does that for you:
This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file.
Also you want to set the flag FILE_APPEND
, so you append your content, e.g.
file_put_contents("templates.txt", $template, FILE_APPEND);
Upvotes: 2