Web Design and Development
Before we begin, it is probably best to start with a disclaimer:
The contact form that we will create here validates user input and minimizes the chance that it could be used improperly, such as for spam. Unfortunately, just about anything on the web can be ‘hacked’ by enterprising hackers. However, this form should thwart most attempts. (See below for more details regarding our release of this code sample, and additional ways to make it hacker proof.)
Alright, ready? Let’s begin. (Want to skip the tutorial? Download all files now.)
A contact form is composed of two main pieces, the HTML which displays the form and the backend code which processes the form. In the code sample below, we’ve provided the HTML which would create a contact form containing a text area and two fields, one for an email address and the other for a name.
<form method="post" action="contact.php">
<input type="text" name="name">
<input type="text" name="email">
<input type="submit" name="submit" value="submit">
The code that processes this form will be a bit more complicated. After all, it needs to accomplish a few things such as:
We will handle each of the above items in turn. Let’s start with with the first item on the list: handling user input.
To handle user input, you need to be able to (1) determine if the form was submitted, and (2) retrieve submitted values. Take a look at the code sample below:
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
In this code sample, we check to see if the form was submitted by checking the value of the variable $_POST['submit']. Then, within the if statement, we retrieve the other form inputs and save them to the variables $name, $email, and $message.
Well, that was easy enough. Now we have to write code to ensure that users fill in all fields.
To make sure that users have entered all required information, you can test each variable as show in the code sample below:
$error = "";
if(trim($name)=="" || trim($email)=="" || trim($message)=="")
$error = "Oops! All fields are required."
In this sample, we have used the PHP trim() function which removes all whitespace. Then we test to see whether or not each variable has a value. If not, the $error variable is set to the error message.
Now onto validating user email addresses. Click below to go to the next page.