How to append a hard file with PHP
August 11th, 2005
At work I needed the following feature for a site:
A user can submit his/her email address via a form and, upon doing so, the email would be stored in a file with the email addresses of all of the other users that submitted their emails. The company wanted it’s visitors to be able to recieve a notification when the new site was launched.
I started by making the form, which ended up looking like this. I decided to echo the form info through PHP, so once the user submitted his/her email address, they would recieve a confirmation message. You’ll see what I mean as we go along.
So here’s the form, echoed:
$out= "Our new and more comprehensive site will be launched shortly.
Please submit your email address if you would like to be notified when it is launched.
“;
Notice I posted to self (sometimes I’m lazy and just drop in the page instead of the PHP server request self page call) and the name of the form and submit is “addemail”.
Next I setup an if command in the page to look for the form submission:
//check to see if email address was submitted
if ($_POST["addemail"]) {
If the email address was submitted, we want to grab with the REQUEST call. We also want to append it with a line breaks to put it on the next line, hence the “\r\n”:
//get the emailaddress
$emailaddress = $_REQUEST["emailaddress"] . “\r\n”;
//open file (in this case called “emails.txt”) to write email to it.
$myFile = “emails.txt”;
//first read the content so we can append
$fR = fopen($myFile, ‘r’) or die(“can’t open file”);
$fcontent = fread($fR, filesize(“emails.txt”));
//output new content with appended email address
$newcontent = $fcontent . $emailaddress;
$fh = fopen($myFile, ‘w’) or die(“can’t open file”);
fwrite($fh, “$newcontent”);
fclose($fh);
//send message to let them know their email address has been added
$out = “Thank you for your interest. You will be contacted in the coming weeks when the new site launches.”;
} else {
//if there was nothing posted, we prepare default display for output.
$out= “Our new and more comprehensive site will be launched shortly.
Please submit your email address if you would like to be notified when it is launched.
“;
}
?>
Then all we have to do is place the content somewhere within the page with this code:
Done!
Leave a Reply