Emailing Form Results

So now we can take information from the various lesson posts and tie it all together to do something wortwhile! I’ve explained how to Retrieve Form Post variables and Send Emails, so how about a comment form that gathers a person’s details and emails them to you?

Okay first you need the form:

<form method="post" action="form-mail.php">
<label for="name">Name:</label> <input type="text" name="name" id="name" size="20" />
<label for="email">Email:</label> <input type="text" name="email" id="email" size="20" />
<label for="comments">Comments:</label> <textarea name="comments" id="comments" cols="30" rows="5"></textarea>
<input type="submit" name="submit" id="submit" value="Submit Form" />

So above we have a simple form (which you would use CSS to style how it is displayed). When the form is submitted it will post the values to the form-mail.php page. This page would contain PHP script at the top to retrieve the form post data, email it to you and then just display a simple thank you page. The PHP script required is:

$name = $_POST['name'];
$from_email = $_POST['email'];
$comments = $_POST['comments'];
$mailbody = "From: ".$name."\n";
$mailbody .= "Email: ".$from_email."\n";
$mailbody .= "Comments: ".$comments;
mail("", "Form Results from Web site", $mailbody, "From:");

Here the code retrieves the information from the _POST array. It then creates a string variable called $mailbody and stored the information into it. Similar to using the print method, but instead of outputting the information to the screen we just save it to a variable instead. The “\n” at the end of each line just means a newline in the plain text email body to make it easier to read. Then the mail() function is run.

This is a very simple example. To expand on this you could (or should) check to ensure that the form fields have had information entered however I’ll give an example of that after I’ve explained control structures 😉

You may also like...

2 Responses

  1. Sarah says:

    Just as a comment now, you can take this post but expand it further with security. In fact this is a must otherwise your form will be hacked and used for spamming.

    Remember the above is the basics to explain how it works, but not a real time example. For further information look to the advanced form post.

  1. Sun, 7 September, 2008

    […] only coming to you. If you found this to start happening then I’d recommend learning how to retrieve individual field values instead. However, for this form we’ll stick with the above as it’s quicker for […]