PHP and Forms

PHP: Submitting a Form to Email with Response Page Redirect

Today I was playing around a bit with PHP and decided to write a post explaining how to send an HTML form to an email address using PHP. I'll also explain how to redirect your page to a thank you or error page based on whether your form submits properly.

Please note that in order to test PHP, you must run your script on a erver. I use MAMP, which installs a local apache server on your machine for free. For Windows users, you can try XAMPP.

First, we'll start off with a simple HTML form:

<form name="contact" method="post" action="contactForm.php">
<label for="Name">First Name:</label>
<input id="name" name="name" type="text" />
<label for ="Email">E-Mail:</label>
<input id="email" name="email" type="text" />
<label for="Message">Message:</label>
<text area name="message" id="message" type="text"/>
<input name="submit" value="Submit" type="submit">
</form>

Notice how the action on the form is set to "contactForm.php". This is the file that we will create to contain our PHP scripts.

In your code editor of choice, open a new file and save it as contactForm.php. The first thing we need to do is set up variables for each of the fields from our form:

$txtName
$txtEmail
$txtMessage

Secondly, we need to use PHP's POST function to collect the values collected from our form:

$txtName = $_POST['name'];
$txtEmail = $_POST['email'];
$txtMessage = $_POST['message'];

Take note that the keys ('name', 'email', and 'message') we are using inside of our POST method match the name value we have set for the fields in our form. The keys must match our name values exactly for our script to function.

If you wanted to test to see that you have called your variables from your form correctly, you could write the following echo statement below your variables:

echo $txtName. $txtEmail. $txtMessage;

Save the file. Open up the form in your browser and test it. You should see the three values that you entered in your form.

In order to have the data sent to an email, we use PHP's mail function.