I am appending a single line of text to the end of a text file, but I always get two copies of the same line of text, appended on the same line, here is the code
<!DOCTYPE html>
<html>
<head>
<title>Store form data in .txt file</title>
</head>
<body>
<form method="post">
Enter Your Text Here:<br>
<input type="text" name="textdata"><br>
<input type="submit" name="submit">
</form>
</body>
</html>
<?php
if(isset($_POST['textdata']))
{
$data=$_POST['textdata'];
$fp = fopen('.email_addresses_test.txt', 'a');
fwrite($fp, $data);
fclose($fp);
}
?>
and a sample image enter image description here
CodePudding user response:
Try:
$data=$_POST['textdata']. "\n";
$fp = fopen('.email_addresses_test.txt', 'a');
fwrite($fp, $data);
fclose($fp);
"\n" in double quotes is interpreted as a line break. http://php.net/manual/en/language.types.string.php
CodePudding user response:
You should use file_put_contents with the FILE_APPEND flag and the LOCK_EX flag to prevent any other process from writing to the file at the same time. These flags are joined with the binary OR operator |
.
$address = "email@domain";
file_put_contents(
".email_addresses_test.txt",
$address . "\n",
FILE_APPEND | LOCK_EX
);