Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a new line on a txt file with PHP?

Tags:

html

php

I Want to create txt file with PHP, that can save the data after input on Form.

So far I have been trying 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 Work fine and can write to file after Input Form, but if I do the second input, the txt file change to the last input.

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

May be the explanation is unclear this the example

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

    Adam, [email protected]
    ===============================
    Second Input:
    Result Txt File:

    Adam, [email protected]
    Eve, [email protected]
    =============================== 

Anyone can help me to Fix it? Im very Appreciated your answer.

Thanks

like image 202
Uchsun Avatar asked Dec 04 '22 07:12

Uchsun


1 Answers

Open the file in append mode:

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

Or use file_put_contents with the FILE_APPEND flag:

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

Note:

If you're running this under a Windows environment, you will need to use \r\n.

I.e.:

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

The \n alone is sufficient under a UNIX/Linux platform but not for Windows.

You can also use the cross-platform PHP_EOL pre-defined constant.

file_put_contents("formdata.txt", $name . "," . $email . PHP_EOL, FILE_APPEND);
like image 93
Barmar Avatar answered Dec 19 '22 22:12

Barmar