Uchsun Uchsun - 10 months ago 54
HTML Question

Write a new line on a txt file with 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


$name = $_POST[name];
$email = $_POST[email];

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

fwrite($fp, $savestring);

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" />

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, Adam@email.com
Second Input:
Result Txt File:

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

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


Answer Source

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);


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


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);