Coding a Minimalist Contact Form with CAPTCHA Spam Protection

Website contact forms are almost a staple of the modern day Internet. Most company websites will have a small contact form where visitors can share their thoughts or suggestions to the webmaster. But there are also so many bots available that these forms can become plagued with spam.

To counter this we need to setup a dynamically generated image called a CAPTCHA. Using PHP we can overlay some text on top of a background texture to build a heightened level of security. But we will also setup the form using jQuery and AJAX to submit the data.

This tutorial is mostly focused on the frontend JavaScript connecting with the backend PHP. It is a bit more advanced than the typical HTML/CSS code, and certainly more challenging. Anybody interested in learning JS/PHP may get lost but keep pushing through! This is a great tutorial for teaching yourself more advanced development techniques. Additionally I’ve provided my source code which you can download and run on your own web server.

Live DemoDownload Source Code

Getting Started

To begin I have created a file named index.php where all our main code will be stored. The form is super easy to follow because we don’t need anything overly confusing. I copied over the HTML below:

<form id="contact" name="contact" method="post" action="index.php" enctype="multipart/form-data">
	<input type="hidden" name="check" value="01">
	<small>*all form fields are required.</small>
	<label for="name" id="namelabel">Name:<span class="err topp">enter your name</span></label>
	<input type="text" name="name" id="name" class="textinput">
	<label for="email" id="emailabel">E-mail:<span class="err topp">enter a valid e-mail address</span></label>
	<input type="email" name="email" id="email" class="textinput">
	<label for="message" id="msglabel">Message:<span class="err txarea">share some stuff with us</span></label>
	<textarea name="message" id="message" class="msgtextarea"></textarea>
	<img src="captcha.php" id="captchaimg">
	<label for="captcha" id="captchalabel">You're not a spammer, right?<span class="err capter">your CAPTCHA code looks wrong</span></label>
	<input type="text" name="captchavalue" id="captchavalue" class="textcaptcha">
	<section id="subber">
	<a href="javascript:void(0);" name="submitlink" id="submitlink" class="btn">Send Message</a>

Each of the span elements inside the label text are used to display error messages. When the user hasn’t correctly filled out an input field the span will fade into view. Also another important point is that we need to setup a PHP session on each page we use. Add this bit to the very top of your HTML index.php page:


The CAPTCHA code is generated randomly each time you refresh the page. This variable of random letters is stored inside a PHP session so we can access it from anywhere. If you do not understand this concept try not to worry much for right now.

Building the CAPTCHA

We should jump into the security portion first, that way we can finish up with validating user input through jQuery. To create this image I am using a simple pattern texture sized appropriately. I’ve also downloaded a small .ttf font from which we’ll use to generate the character strings.

In the same directory as our index file create a new one called captcha.php. This will actually output image data directly to the browser, so we call this URL in an HTML img tag. The code isn’t too confusing but I’ll break it down here.


$im = imagecreatefrompng("./captcha.png");

$chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 't', 'u', 'v', 'w', 'x', 'y', 'z');
$str1 = $chars[mt_rand(0, count($chars)-1)];
$str2 = $chars[mt_rand(0, count($chars)-1)];
$str3 = $chars[mt_rand(0, count($chars)-1)];
$str4 = $chars[mt_rand(0, count($chars)-1)];
$font = "creativeblock.ttf";
$size = mt_rand(14, 18);

Once again I’ve applied the session_start() function so we can store the variable data between pages. I am using another PHP function imagecreatefrompng() with the background texture I supplied. The array of letters is used as a storage vault to pull from and generate the unique image.

Each of the variables str1-4 is a unique one-letter string. When combined together we generate four unique letters using the font creativeblock.ttf. We have also set the font size to randomize between 14-18 pixels, but you should customize this if needed.

Security Variables

We want to setup the PHP session variable to first hold our unique CAPTCHA in memory. Then we can setup some other display variables like the font angle, color, and size.

$_SESSION['captcha'] = $str1.$str2.$str3.$str4;

$angle = mt_rand(-5, 5);
$color = imagecolorallocate($im, 55, 55, 55);
$textsize = imagettfbbox($size, $angle, $font, $textstr);

$twidth = abs($textsize[2]-$textsize[0]);
$theight = abs($textsize[5]-$textsize[3]);

$x = mt_rand(5, 60);
$y = mt_rand(18, 35);

imagettftext($im, $size, $angle, $x, $y, $color, $font, $str1);
imagettftext($im, $size, $angle, $x+mt_rand(20, 25), $y+mt_rand(1, 3), $color, $font, $str2);
imagettftext($im, $size, $angle, $x+mt_rand(45, 50), $y+mt_rand(1, 3), $color, $font, $str3);
imagettftext($im, $size, $angle, $x+mt_rand(65, 70), $y+mt_rand(1, 3), $color, $font, $str4);

The $x and $y variables are used to move text up/down and left/right along the image. Each time you refresh the page you’ll notice the letters have positioned themselves differently. This is done by another function called imagettftext(). Each of the four lines of code will apply all our variables and stamp each of the letters onto the BG image.

// Output the image 
header("Content-type: image/png"); 

Now we set the document headers as an image type and directly output the image content. A typical website Content-type is text/HTML or something similar. But PHP is powerful enough to force an image type even with a .php file extension. Also since each image is generated dynamically we destroy the cached version from memory to clear up server resources.

Testing the Session Input

Let’s create one more file in the same directory named captcha_check.php. We only need a few lines of code here to verify if the user has input a value which matches the current captcha text. We can do this simply by accessing the $_SESSION variable we setup earlier.


$userval = strtolower(trim($_POST['captchavalue']));
$thecapt = strtolower($_SESSION['captcha']);

if($userval == $thecapt) { echo "true"; }
else { echo "false"; }

The first $userval variable is what the user enters, and we retrieve that via Ajax. $thecapt contains our session variable for the current text displayed in our CAPTCHA image. We put both of the strings into lowercase and remove any extra whitespace, then call a simple if/else logic statement. We can check if the result is “true” or “false” inside jQuery.

JS Checks and Balances

I’ve already included the jQuery 1.7.2 library in a script tag in my document header. But we also want to open a new script tag at the very bottom of the page, directly before the closing </body> tag. Then inside let’s write a small function call to handle dynamic verification.

	$("#contact").submit(function() { return false; });
	$("#submitlink").on("click", function(e){
		var usercaptvalue = $("#captchavalue").val();
		var subnamevalue  = $("#name").val();
		var emailvalue    = $("#email").val();
		var msgvalue      = $("#message").val();
		var postchecks = userSendMailStatus(subnamevalue, emailvalue, msgvalue, usercaptvalue);

Once the DOM is loaded we first disable the HTML form so it can never be submitted via input. Then I’m using the .on() event handler to check whenever a user clicks on the submit link, and we call a series of functions. We setup a unique variable for each of the input fields and pass these into a function userSendMailStatus().

I’ll admit this is a very long function call since it contains basically all of our verification code. I’ll try to break it down into smaller chunks so we can follow the logic a bit easier. But if you get lost don’t hesitate to download my example code and go through to compare with your own.

Custom User Verification

First let me introduce a small bit of code which I’ve written all above the previous block. All our functions are written above the $(document).ready() statement so they’re ready in advance.

function checkValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-+\s]+")|([\w-+]+(?:\.[\w-+]+)*)|("[\w-+\s]+")([\w-+]+(?:\.[\w-+]+)*))(@((?:[\w-+]+\.)*\w[\w-+]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][\d]\.|1[\d]{2}\.|[\d]{1,2}\.))((25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\.){2}(25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\]?$)/i);
    return pattern.test(emailAddress);

var mailsendstatus;

The checkValidEmailAddress() is using very complex regular expressions to verify if the user input looks like a normal e-mail. Don’t worry if you can’t understand the code, just know that it works and we can call it from anywhere! Also the mailsendstatus variable is declared but set to NULL so that we can set the value in our new function.

function userSendMailStatus(uname, uemail, umsg, ucaptcha) {
	// checking for some valid user name
	if(!uname) {
	else if(uname.length > 3) {
	// checking for valid email
	if(!checkValidEmailAddress(uemail)) {
	else if(checkValidEmailAddress(uemail)) {
	// checking for valid message
	if(!umsg) {
	else if(umsg.length > 5) {

The first 3 statements are all very typical checking for an empty(or invalid) name, e-mail, and message field. These if/elseif statements control the display of each error message. They will fade in and out based on the current value of each input field.

Sending Out the E-mail

The rest of the function is using the jQuery .ajax() method which requires some advanced knowledge. But I’ll try to break it all down into simpler terms, don’t worry if you can’t follow everything.

	// ajax check for captcha code
			type: 'POST',
			url: 'captcha_check.php',
			data: $("#contact").serialize(),
			success: function(data) {
				if(data == "false") {
					mailsendstatus = false;
				else if(data == "true"){
					if(uname.length > 3 && umsg.length > 5 && checkValidEmailAddress(uemail)) {
						// in this case all of our inputs look good
						// so we say true and send the mail
						mailsendstatus = true;
						$("#subber").html('<img src="load.gif" alt="loading...">');

								type: 'POST',
								url: 'sendmail.php',
								data: $("#contact").serialize(),
								success: function(data) {
									if(data == "yes") {
									$("#contactwrapper").slideUp(650, function(){
										$(this).before("<strong>Yep your mail has been sent!</strong>");
						); // close sending email ajax call	
					} // close if logic for mailsendstatus true
				} // close check CAPTCHA return true
			} // close ajax success callback function
		} // close ajax bracket open
	return mailsendstatus;

We’re actually using two different Ajax calls for two different .php files. The first is checking against our captcha_check.php to see if the image text matches the user input. If not we display the error, but if so we then also check all 3 other fields.

If all four of the user input fields are not blank and validate then we set mailsendstatus to true. This is also where we call the 2nd ajax function to a new file sendmail.php. All of this code is very typical boilerplate for sending an HTML e-mail in PHP. And the return data is either a “yes” or “no” determining if the e-mail was sent or not. If successful we slowly hide the form and append new text letting the user know we sent their message.

The sendmail.php file isn’t totally groundbreaking compared to the rest of our code. I haven’t copied it over since it’s slightly arbitrary to the JS/CAPTCHA verification. But definitely check out the demo source and go through if you need more helpful documentation.

Live DemoDownload Source Code


Building a website contact system is very tricky and does require at least intermediate programming knowledge. The more you practice web development the more comfortable you’ll feel building your own small web apps. Hopefully this tutorial can act as a guide to deeper learning. If you have any comments or questions feel free to share with us in the post discussion area below.