You are developing a web site or web application and are wondering how you can build a secure contact form for your visitor to contact you from the website easily while controlling spam.
Here, we are going to walk you through the process of building out a contact form from scratch
using PHP with a Captcha to protect the contact form from spam.
Normally, there are many ways to build and validate a form in php:
- you can write code validation of you form in different file than
the file containing the form itself,
- you can write code validation of your form in the same file than
the form. for this tutorials,
we choose to write contact form and code validation in the same file.
So what are we going to build?
- We are going to develop a contact form in which name, email,
message and captcha should be typed prior to the form to be send
to the specified email, subject of the contact information
would not be mandatory to submit the form.
- The email should have a valid email address format.
- Our contact form would look like the contact form below:

With validation's criteria on each field. After having hit the submit
button, the informations of the contact form should be send to
an email address.
So let’s get started by creating our file contact-form.php that
would containt 2 parts:
1- The code to create the form itself like below:
<form method="post" action="contact_us.php" id="contactform">
<label><h2> Contact Form</h2></label><br/><br/>
<label>Name</label><br/>
<input type="text" name="name" placeholder="Type name Here " /><br/>
<label>Email</label><br/>
<input name="email" type="email" placeholder="Type email Here "/> <br/>
<label>Subject</label><br/>
<input type="text" name="subject" placeholder="Type subject Here " /> <br/>
<label>Message</label><br/>
<textarea name="message" rows="20" cols="20" placeholder="Type message Here">
</textarea><br/>
<!--captcha.php is a php file that create a picture in php and show it as .png
and in this form it is used as image source-->
<label>Please type this captcha to avoid spam <img src="captcha.php"><br/>
</label>
<input type="text" name="code" placeholder="Type captcha code Here "> <br/>
<input id="submit" name="submit" type="submit" value="Submit"/>
</form>
|
Explanation of the contain of the form tags above:
-The contact-form page has the .php extension so it can expect and process PHP
code because we decide to include code validation and form in the same file;
-The tag <form> has an ‘action’ attribute which allow to specify the file that’s
going to send the form’s data to ( means the file that would validate de form),
for our case it is the same file contact-form.php which will contain code
to validate form;
-The ‘method’ attribute specify how we want our data to be handled and sent,
we use here the ‘POST’ method because it is more secure than the GET method
(GET will display the data in the URL when data would be send from the
contact form).
-All form fields have a ‘name’ attribute, PHP uses the values from the name
attributes to fetch their data.
-The last fields of the form is an input of type"submit" to allow to send
informations in the form.
Let take this part of the source code above and explain what it would do:
<label>Name</label><br/> <input type="text" name="name"
placeholder="Type name Here " /><br/>
|
This would create a label " Name" and an input of type "text"
where the name would be typed then the attribute placeholder would add
a text "Type name Here " in the text zone like a default text.
The source code would do almost the same for the email, the subject
and the message of the contact form, but for the message it would be a
textarea.
To create the captcha in the form:
- The code's lines below:
<label>Please type this captcha to avoid spam <img src="captcha.php"><br/></label>
<input type="text" name="code" placeholder="Type captcha code Here "> <br/>
|
Would create an < img > tag in the form using as source the contain of another
php file called captcha.php. So to allow the captcha to work in the form above,
we have to create this other php file called captcha.php which would contains
the following code:
Captcha.php
<?php session_start(); // start a session
$image = imagecreate(60, 20); //create //blank image (width, height)
$bgcolor = imagecolorallocate($image, 0, 0, 0); //add black
//background color with RGB to the image created.
$textcolor = imagecolorallocate($image, 255, 255, 255); //add text
//code color with RGB. $code = rand(1000, 9999); //create a random
//number between 1000 and 9999
$_SESSION['code'] = ($code); //add the random number to session 'code'
imagestring($image, 10, 8, 3, $code, $textcolor); //create image
//conataining as image with all the settings above.
header ("Content-type: image/png"); // define image type as .png
imagepng($image); //display image as PNG
?>
|
We have commented the captcha.php file at each line, but what we can
notice here is that this code create a black picture of size 60*20, generate
a random number between 1000 and 9999, and show the image with the
random number generated on the black image.
- The "session_start()" in the beginning of the captchat.php is to allow
us to save the generated random number of the image on the server
and validate it in the form, so the $_SESSION['code'] = ($code) save
the value of the random number into the session so that we can compare
it later with the value that the user would have typed in the captcha
field in the contact form.
2- The code that validate the contain of the contact form:
You can choose to write this validation code before the tag <form>
of your contact form or after it, I choose to do it before the <form> tag,
here is the code:
<?php
/*if submit button is hitting*/
if (isset($_POST['submit']))
{ $error="";
//-----------------------------------------
if (!empty($_POST['name']))
{ $name = $_POST['name']; }
else
{ $error .= "You didn't type in your name. <br />"; }
//-----------------------------------------
if (!empty($_POST['email']))
{ $email = $_POST['email'];
if(!preg_match("/^[_a-z0-9]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email))
{ $error .= "The e-mail address you entered is not valid. <br/>"; }
}
else
{ $error .= "You didn't type in an e-mail address. <br />"; }
//-----------------------------------------
if (!empty($_POST['subject']))
{ $subject=$_POST['subject']; }
else
{ $message.=" you didn't type a subject<br/>";}
//-----------------------------------------
if (!empty($_POST['message']))
{ $message = $_POST['message']; }
else
{ $error .= "You didn't type in a message. <br />"; }
//-----------------------------------------
if(($_POST['code']) == $_SESSION['code'])
{ $code = $_POST['code'];}
else
{$error .= "The captcha code you entered does not match. Please try again. <br />";}
// test if error is empty mean we have nothing to send else we send the
if (empty($error))
{ $from = 'From: ' . $name . ' <' . $email . '>';
// i.e. From John S. <Marc.sid@email.com>
$to = "webmaster@technologytuto.com ";
// here you would write the email address you
// want the information of the contact form to be send to
$subject = "New contact form message";
$content = " M./Mrs " .$name . " has sent you a message: \n" . $message;
$success = "<h3>Thank you! Your message has been sent, we will initiate a contact
with you very soon!</h3> <br/>";
mail($to,$subject,$content,$from);
echo $success; }
else { echo '<p class="error"><strong>Your message have not been sent<br/>
The following error(s) returned:</strong><br/>' . $error . ' Please,
fill out the contact form again</p>';
}
} // end (isset($_POST['submit'])
?>
|
Explanation of the code above validating the contact form:
In This code, the statement if (isset($_POST['submit'])) checks if the
submit button is hitting before doing any control on form's fields,
if yes it create an empty variable $error that would contain the message
error each time. Then, each field would be control before using it:
- The field "name", "subject" and "message" would be validate the same
way by the code which verify if the field is not empty using
if (!empty($_POST['name'])) for the name, if yes it save the
value typed if not if add an error message in the variable error created
previously.
- The email is validated using the same process than the field "name"
but to make sure that the email typing in the form match with the
good email's format, the code
if (!preg_match("/^[_a-z0-9]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)
*(\.[a-z]{2,3})$/i", $email))
is used. You don't need to memorize the pattern use to check the
email format, just copy it an keep it somewhere for future needs
because the email format is still the same and known.
- The captcha is validated using the code
if(($_POST['code']) == $_SESSION['code']), which
compare the typed code and the stored code into the
variable "$code"of the session from the captcha.php file
and save or add an error on the existing error message if it
doesn't match.
After all validation's field syntax, if the error message is empty ,
it means that all fields have been properly filled out and that
the email typed has the good email's format, in this case the
information of the contact form are sent to the email specified
in variable $to using the code: mail($to,$subject,$content,$from);
and a success message that have been saved in the variable $success
is showed by the code echo $success; and in the case that the
error message is not empty nothing is sent and the contain of the
errors message is shown above the form to specify to the visitor
his error when typing in the form. Then the style sheet to
format the form will be like this:
styleecran.css
#contactform
{
margin:0 auto;
width:459px;
padding: 10px;
border: 1px solid #17375e;
background-color:#e7e7e7;
position: relative; left:20%; }
|
If you have already a .css file for your web application, you can just add the
source code above in this file, if not you should create one and don't forget
to specify the name of the .css file in the <head> </head> tag of your file
name contact-form.php. On this case the styleecran.css file is located
in the folder "css" situated in the root directory of the web application.
the code of styleecran.css file above would make the form has a grey
background, and would positionning it relatively a 20% from the left
according to its previous position.
<link rel="stylesheet" href="css/styleecran.css" type="text/css" media="screen"/>
|
The entire code source of the contact form would look like this:
contact-form.php
<?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact form</title>
<link rel="stylesheet" href="css/styleecran.css" type="text/css" media="screen"/>
</head>
<body>
<header> </header>
< section>
<?php
/*if submit button is hitting*/
if (isset($_POST['submit']))
{
$error="";
//-----------------------------------------
if (!empty($_POST['name']))
{ $name = $_POST['name']; }
else { $error .= "You didn't type in your name. <br />"; }
//-----------------------------------------
if (!empty($_POST['email']))
{ $email = $_POST['email'];
if (!preg_match("/^[_a-z0-9]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)
*(\.[a-z]{2,3})$/i", $email))
{ $error .= "The e-mail address you entered is not valid. <br/>"; }
}
else { $error .= "You didn't type in an e-mail address. <br />"; }
//-----------------------------------------
if (!empty($_POST['subject']))
{ $subject=$_POST['subject']; }
else { $message.=" you didn't type a subject<br/>"; }
//-----------------------------------------
if (!empty($_POST['message']))
{ $message = $_POST['message']; }
else { $error .= "You didn't type in a message. <br />"; }
//-----------------------------------------
(($_POST['code']) == $_SESSION['code'])
{ $code = $_POST['code']; }
else {
$error .= "The captcha code you entered does not match. Please try again.
<br />"; }
// test if error is empty mean we have nothing to send else we send the
if (empty($error))
{ $from = 'From: ' . $name . ' <' . $email . '>';
// i.e. From John S. <john.smith@mail.com>
$to = "webmaster@technologytuto.com";
$content = " M./Mrs " .$name . " has sent you a message: \n" . $message;
$success = "<h3>Thank you! Your message has been sent,
we will initiate a contact with you very soon! <br/>";
mail($to,$subject,$content,$from); echo $success;
}
else { echo '<p class="error"><strong>Your message have not been sent<br/>
The following error(s) returned:</strong><br/>' . $error . ' Please,
fill out the contact form again</p>';
}
} // end (isset($_POST['submit'])
?>
/*-------------------- contact form itself--------------*/
<form method="post" action="contact_us.php" id="contactform">
<!-- placeholder is an attribut to set a default value to our input that would
stay if no value is enter-->
<label><h2> Contact Form</h2></label><br/><br/>
<label>Name</label><br/>
<input type="text" name="name" placeholder="Type subject Here " /><br/>
<label>Email</label><br/> <input name="email" type="email"
placeholder="Type email Here "/>
<br/> <!--placeholder="Type Here " would add a text in
the text zone like a default text-->
<label>Subject</label><br/> <input type="text" name="subject"
placeholder="Type subject Here"/>
<br/> <label>Message</label><br/>
<textarea name="message" rows="20" cols="20"
placeholder="Type message Here ">
</textarea><br/>
<!--captcha.php is a php file that create a picture in php and show
it as .png and here is used as image source-->
<label>Please type this captcha to avoid spam <img src="captcha.php">
<br/>
</label>
<input type="text" name="code" placeholder="Type captcha code Here ">
<br/>
<input id="submit" name="submit" type="submit" value="Submit"/> </form>
//----- end contact form--------
</section>
<footer> </footer>
</body>
</html>
|
Note: Each field you want to add to the contact form would be
added the same way:
- First by adding it in the contact-form.php file specialy
into the < form> tag as others fields, and then, the code
to validate it would be added in the validation part like the validation
code of other fields. Sometime the validation code can
lightly change according to what you want to control.
If you like this post or have used the code above, please consider
give us a feed back of your experience in using this code to
have a contact form with spam protection(captcha)in
your web application!