Question : Write Form to Text File - Add Text Instead of Overwrite? PHP

I have an email list signup form on a website with only one field called "email". The code below works to write the email form field to a text file: emaillist.txt. However, it only shows the last email submitted. I want it to add the email and create a list instead of just overwriting the last entry. Also, at the end I'd like it to go to a page called thankyou.php instead of displaying a message.

<?php
$ourFileName = "emaillist.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fclose($ourFileHandle);

$email=$_POST['email'];
if ($email!='') {
   $input = $email;
   file_put_contents("emaillist.txt", $input .", " , FILE_APPEND );
   echo "Thank you for your input! Your choice has been saved...";
}
?>


Thanks, Gary

Answer : Write Form to Text File - Add Text Instead of Overwrite? PHP

<?php
$ourFileName = "emaillist.txt";

$email=$_POST['email'];
if ($email!='') {
// add a line break to have only one e-mail address per line
   $input = $email . "\n";

// opening with fmode w will overwrite the file every time you write a new e-mail address
   $ourFileHandle = fopen($ourFileName, 'a') or die("can't open file");

// use fwrite to make use of the open file. Closing it and reopening it for file_put_contents()
// are unnecessary file operations
   fwrite($ourFileHandle, $input);
   fclose($ourFileHandle);
   header ('Location: http://www.example.com/thankyou.php');
}
?>
Random Solutions  
 
programming4us programming4us