SpyreStudios

Web Design and Development Magazine

  • Design
  • Resources
  • Showcase
  • Inspirational
  • Tutorials
  • CSS
  • Resources
  • Tools
  • UX
  • More
    • Mobile
    • Usability
    • HTML5
    • Business
    • Freebies
    • Giveaway
    • About SpyreStudios
    • Advertise On SpyreStudios
    • Get In Touch With Us

Coding a Minimalist Contact Form with CAPTCHA Spam Protection

June 18, 2012 by Jake Rocheleau

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 Demo – Download 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>
	</section>
</form>

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:

<?php
session_start();
?>

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 dafont.com 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.

<?php
session_start(); 

$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"); 
imagepng($im);
imagedestroy($im);

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.

session_start();

$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.

$(document).ready(function(){
	$("#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) {
		$("#namelabel").children(".err").fadeIn('slow');
	}
	else if(uname.length > 3) {
		$("#namelabel").children(".err").fadeOut('slow');		
	}
	
	// checking for valid email
	if(!checkValidEmailAddress(uemail)) {
		$("#emailabel").children(".err").fadeIn('slow');
	}
	else if(checkValidEmailAddress(uemail)) {
		$("#emailabel").children(".err").fadeOut('slow');	
	}
	
	// checking for valid message
	if(!umsg) {
		$("#msglabel").children(".err").fadeIn('slow');
	}
	else if(umsg.length > 5) {
		$("#msglabel").children(".err").fadeOut('slow');
	}

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
	$.ajax(
		{
			type: 'POST',
			url: 'captcha_check.php',
			data: $("#contact").serialize(),
			success: function(data) {
				if(data == "false") {
					mailsendstatus = false;
					$("#captchalabel").children(".err").fadeIn('slow');
				}
				else if(data == "true"){
					$("#captchalabel").children(".err").fadeOut('slow');
					
					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...">');

						$.ajax(
							{
								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 php.net if you need more helpful documentation.

Live Demo – Download Source Code

Conclusion

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.

Filed Under: Tutorial Tagged With: captcha, contact, css3, html5, jquery, php, tutorial, web development

Recent Posts

  • How to Choose a Stunning Font Package for Your Brand
  • 31 Fresh Design Elements for Spring and Easter
  • 10 Templates for Music Concert Flyers
  • How to Build a Web Scraper Using Node.js
  • Best PHP Books, Courses and Tutorials in 2022

Archives

  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021
  • May 2021
  • April 2021
  • March 2021
  • February 2021
  • January 2021
  • December 2020
  • November 2020
  • October 2020
  • September 2020
  • August 2020
  • July 2020
  • June 2020
  • May 2020
  • April 2020
  • March 2020
  • February 2020
  • January 2020
  • December 2019
  • November 2019
  • October 2019
  • September 2019
  • August 2019
  • July 2019
  • June 2019
  • May 2019
  • April 2019
  • March 2019
  • February 2019
  • January 2019
  • December 2018
  • November 2018
  • October 2018
  • September 2018
  • August 2018
  • July 2018
  • June 2018
  • May 2018
  • April 2018
  • March 2018
  • February 2018
  • January 2018
  • December 2017
  • November 2017
  • October 2017
  • September 2017
  • August 2017
  • July 2017
  • June 2017
  • May 2017
  • April 2017
  • March 2017
  • February 2017
  • January 2017
  • December 2016
  • November 2016
  • October 2016
  • September 2016
  • August 2016
  • July 2016
  • June 2016
  • May 2016
  • April 2016
  • March 2016
  • February 2016
  • January 2016
  • December 2015
  • November 2015
  • October 2015
  • September 2015
  • August 2015
  • July 2015
  • June 2015
  • May 2015
  • April 2015
  • March 2015
  • February 2015
  • January 2015
  • December 2014
  • November 2014
  • October 2014
  • September 2014
  • August 2014
  • July 2014
  • June 2014
  • May 2014
  • April 2014
  • March 2014
  • February 2014
  • January 2014
  • December 2013
  • November 2013
  • October 2013
  • September 2013
  • August 2013
  • July 2013
  • June 2013
  • May 2013
  • April 2013
  • March 2013
  • February 2013
  • January 2013
  • December 2012
  • November 2012
  • October 2012
  • September 2012
  • August 2012
  • July 2012
  • June 2012
  • May 2012
  • April 2012
  • March 2012
  • February 2012
  • January 2012
  • December 2011
  • November 2011
  • October 2011
  • September 2011
  • August 2011
  • July 2011
  • June 2011
  • May 2011
  • April 2011
  • March 2011
  • February 2011
  • January 2011
  • December 2010
  • November 2010
  • October 2010
  • September 2010
  • August 2010
  • July 2010
  • June 2010
  • May 2010
  • April 2010
  • March 2010
  • February 2010
  • January 2010
  • December 2009
  • November 2009
  • October 2009
  • September 2009
  • August 2009
  • July 2009
  • June 2009
  • May 2009
  • April 2009
  • March 2009
  • February 2009
  • January 2009
  • December 2008
  • November 2008
  • October 2008
  • May 2008
  • April 2008

Categories

  • Accessibility
  • Android
  • Apps
  • Art
  • Article
  • Blogging
  • Books
  • Bootstrap
  • Business
  • CSS
  • Design
  • Development
  • Ecommerce
  • Fireworks
  • Flash
  • Freebies
  • Freelance
  • General
  • Giveaway
  • Graphic Design
  • HTML5
  • Icons
  • Illustrator
  • InDesign
  • Infographics
  • Inspirational
  • Interview
  • Jobs
  • jQuery
  • Learning
  • Logos
  • Matrix
  • Minimalism
  • Mobile
  • Motion Graphics
  • Music
  • News
  • Photoshop
  • PHP
  • Promoted
  • Rails
  • Resources
  • Showcase
  • Tools
  • Tutorial
  • Twitter
  • Typography
  • Uncategorized
  • Usability
  • UX
  • Wallpapers
  • Wireframing
  • WordPress
  • Work

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org

SpyreStudios © 2022