Using Captcha on your Contact Forms

Do you own a website with contact forms? If so, I am sure you won’t want your email address to be harvested by spammers, right?

Now, how do we actually secure the email address? One solution is a Captcha.

Captcha is a type of test to ensure that the visitor on your site is not generated by a computer. Of course, it is not 100% effective, but at least it prevents most spammers from doing so.

Below are some examples of Captcha.

Captcha Tests

Examples of Captcha Test. The top row shows the usual captcha tests, the middle one shows a harder one and the bottom Captcha shows a Mathematical Question.

Implementing Captcha is easy (Just visit a website that gives free Captcha services), but how about making your own?

Let us start off by making our own Captcha Code Generator. How about naming it Captcha.php? Note that this requires a web server that supports PHP with the PHP GD Library installed.

Source Code for Captcha.php

<?php
session_start();
$code= '';
for ($a=0;$a<5;$a++) {
	$code.= chr(rand(97, 122));
}
$_SESSION['captcha'] = $code;
$image = imagecreatetruecolor(170, 60);
$color = imagecolorallocate($image, 89, 136, 201);
$white = imagecolorallocate($image, 255, 255, 255);
imagefilledrectangle($image,0,0,399,90,$white);
imagettftext ($image, 30, 0, 10, 40, $color, "/arial.ttf", $_SESSION['rand_code']);
header("Content-type: image/png");
imagepng($image);
?>

Interpretation of Source Code

<?php // Start of php
session_start(); // Start a session
$code= ''; // Make a variable called code (can be called from forms later on)
for ($a=0;$a<5;$a++) { // Loop to generate a random character for the code.
	$code.= chr(rand(97, 122)); //Adds the random lower case character to the code
}
$_SESSION['captcha'] = $code; //Variable code is now available for use - Known as "captcha" for other pages
$image = imagecreatetruecolor(170, 60); //Generate an image
$color = imagecolorallocate($image, 89, 136, 201);
$white = imagecolorallocate($image, 255, 255, 255);
imagefilledrectangle($image,0,0,399,90,$white); //Fill the image with white background
imagettftext ($image, 30, 0, 10, 40, $color, "/arial.ttf", $_SESSION['rand_code']); // Generate Captcha using a custom font (You must upload the font file)
header("Content-type: image/png"); //Make the Captcha a image file
imagepng($image); // Generate it as a image file
?> //End of php

Implementing the Captcha Code

Assuming you have a contact form at hand, let’s implement the captcha code.

Your current code should look something like this.

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data"> //Change your current one to this
	Your Name: <input type="text" name="name" /><br />
	Your Email: <input type="text" name="email"/><br />
	Your Enquiry:<br />
       <textarea name="message" cols="50" rows="10"></textarea><br />
    <input type="submit" name="submit" value="Send" class="button" />
</form>

Add this in between the textbox area for the message and the Send button.

<img src="Captcha.php"/><br />
Verification Code: <input type="text" name="code" /><br />
<?php
session_start();
if(isset($_POST['submit'])) {
		if($_POST['code'] == $_SESSION['captcha']) {
                        mail('Your Email Address', 'Subject of Email', $message, 'From: ' . $email);
                }
                else {
			$error = "Please type the verification code again.";
		}
}
?>

You may consider adding an alert for users who entered the wrong Captcha code.

Place the below code above the form or anywhere you desire it to be. The error message is specified in the code snippet above.

<?php if(!empty($error)) echo '<h3><font color="#FF0000;">'.$error.'</font></h3><br /><br />'; ?>

Now that you have completed your contact form with an easy Captcha, you can soon make your own complicated Captcha and contact forms!

It’s time to take a look at what the contact form looks like!

Contact form with simple Captcha

Contact form with simple Captcha

Error Message

Error Message displayed above the form if the user entered the wrong code.

Have fun with Captcha and your contact form!

If you have any problems or need help with HTML/PHP, feel free to leave a comment and I will attend to it :)

Liked this article? Share it with your friends.

By
Creastery is a developer and one of the founders of TechAirlines. He enjoys almost everything about technology, including animations, programming, web development and also honing his hacking skills at several challenge sites.

  • http://www.techairlines.com Brian Yang

    Useful tutorial! :)

    I prefer to use the reCAPTCHA service as the ones generated by them seem to be the most effective against spam bots. In addition, it’s helping to digitize books.

    Unfortunately, there are tons of spam bots out there and many have developed systems that can solve many captchas, but they certainly do slow them down.

  • http://www.creastery.com Creastery

    :) Thanks for the comment.
    reCAPTCHA is nice (its the 3rd type of captcha of the first row in the 1st picture) with the dots and wavy words.
    I like the cat most!
    I will make a script with the same concept soon :)