Write a new line in a txt file with PHP?

I want to create a txt file with PHP that can save data after input to Form.

So far, I have been trying to use this script.

<?php

if(isset($_POST[S1]))
{
   $name = $_POST[name];
   $email = $_POST[email];

   $fp = fopen("formdata.txt", "w") or exit("Unable to open file!");
   $savestring = $name . "," . $email . "\n";

   fwrite($fp, $savestring);

   fclose($fp);
   echo "<h1>You data has been saved in a text file!</h1>";

?>
<form name="web_form" id="web_form" method="post" action="coba.php">
        Enter name: </label><input type="text" name="name" id="name" />
        Enter email: </label><input type="text" name="email" id="email" />
        <input type="submit" name="S1" id="s1″ value="Submit" />
</form>

It works fine and can be written to the file after the input form, but if I do the second input, the txt file changes to the last input.

How can I do when the second input, the last input writes a new line to a txt file?

Maybe the explanation is unclear what an example

    ===============================
    First Input:
    Result Txt File:

    Adam, Adam@email.com
    ===============================
    Second Input:
    Result Txt File:

    Adam, Adam@email.com
    Eve, Eve@gmail.com
    =============================== 

Can anyone help me fix this? I really appreciated your answer.

thank

+4
source share
1 answer

Open the file in upload mode:

$fp = fopen("formdata.txt", "a") or exit("Unable to open file!");

Or use file_put_contentswith flag FILE_APPEND:

file_put_contents("formdata.txt", $name . "," . $email . "\n", FILE_APPEND);

Note:

Windows, \r\n.

:.

file_put_contents("formdata.txt", $name . "," . $email . "\r\n", FILE_APPEND);

\n UNIX/Linux, Windows.

- PHP_EOL .

file_put_contents("formdata.txt", $name . "," . $email . PHP_EOL, FILE_APPEND);
+14

Source: https://habr.com/ru/post/1529916/


All Articles