Hello. I have a new blog.

I've moved this blog to the following URL Kerkness.ca. Thank you for visiting, please update your bookmarks.

Saturday, April 5, 2008

Simple PHP Captcha

One of the contact forms on a business web site I run has been getting a lot of spam attempts submitted to it. These attempts don't go anywhere but it's becoming a bit of a hassle anyway. Time to add some sort of Captcha to the form.

What is Captcha? (from Wikipedia) A Captcha is a type of challenge-response test used in computing to determine that the user is not run by a computer. The process involves one computer (a server) asking a user to complete a simple test which the computer is able to generate and grade. Because other computers are unable to solve the CAPTCHA, any user entering a correct solution is presumed to be human. A common type of CAPTCHA requires that the user type the letters of a distorted image, sometimes with the addition of an obscured sequence of letters or digits that appears on the screen.

The term "CAPTCHA" was coined in 2000 by Luis von Ahn, Manuel Blum, Nicholas J. Hopper (all of Carnegie Mellon University), and John Langford (then of IBM). It is a contrived acronym for "Completely Automated Public Turing test to tell Computers and Humans Apart", trademarked by Carnegie Mellon University.

Example with code.

Here is a simple PHP script which will generates a Captcha and logs the response in a _SESSION variable. It requires GD support on the server. The script uses a randomly selected background image (img1.jpg, img2.jpg, img3.jpg or img4.jpg) and adds the pass key over top of background.

PHP Captcha Script.

// Start sessions
session_start();

// Create a random string
$fullhash = md5(microtime());

// Select the first 5 characters of string to use as pass code
$captcha = substr($fullhash,0,5);

// Select random image filename for use as background
$imgrand = rand(1,4);
$imgfile = 'img'.$imgrand.'.jpg';

// Create new image using the background image as a template
$image =imagecreatefromjpeg($imgfile);

// Set colors to use for Captcha text
$txtcolor = imagecolorallocate($image, 255, 255, 255);
$shadowcolor = imagecolorallocate($image, 0, 0, 0);

// Layer Captcha text over image
imagestring($image, 6, 21, 11, $captcha, $shadowcolor);
imagestring($image, 5, 20, 10, $captcha, $txtcolor);

// Add pass code to _SESSION variable
$_SESSION['captchakey'] = $captcha;

// Adjust header and output image
header("Content-type: image/jpeg");
imagejpeg($image);


Usage Example

Inside a form add the following image tag along with an input field for the user to enter the pass code into. When validating the form check the user submitted info against the _SESSION variable 'captchakey'
<img src="captcha.php">
Click here to see a demo.
Click here to copy my background images.

No comments:

Post a Comment

Thank you for the comments.