In this tutorial I will show you how to create a simple contact form with PHP. With the help of a contact form your visitors will fill out a form and its content will be send to you via email.
Step 1. First of all let’s try to find out what we need in this project. We want that a visitor can send us a message but we don’t want to show our real email address to avoid any spam. We need all the information from the visitor to be able to send a replay to him which means generally a valid email address. To make our work easier we can introduce a subject field just to know what the message is all about. Besides this it would be fine if we could address our replay with the name of the visitor.
So the summary of the important user inputs:
Subject
Message
Name
Email
Besides this the main functional area – what we should implement - are the followings:
Creating a HTML form
Displaying error messages on the form if necessary
Validating user input
Sending the message via email
Display a thank you message if everything was success.
In the next step we begin with some coding.
Step 2. Let’s make some coding as well. As we discussed before the form contains 4 inputs. Three of them are normal text fields for the subject, name and email and we have a text area for the message itself. Besides this we extend the form to be able to display any error message (see later) and to remember the visitor’s entries (see later as well).
We want to show the form only until it is not filled correctly. If everything is ok than we will display a Thank you message instead of the form. To realize this we will put the form code into a PHP function and call it only if needed. As parameter we will provide field values and error messages if necessary.
The function looks definition like this:
<?php function createForm($subject="",$name="",$email="",$message="",$error1="",$error2="",$error3="") ?>
Step 3. As next step we will implement the main HTML code. Here we first check whether the form was submitted or not. If the form was not submitted than call the above created function to display the form. If the form was submitted than store the values from the $_POST variable and make some validation with it (see details later). If any error occurs than we will display the form again but in this time we will prepare the form with the submitted values and error message(s). With this we can help our visitor to find the problem and solve it without type everything again.
In case of validation was success than we will send the mail (see details later) and display the Thank you message.