PHP Captcha script tutorial

Captcha image verification method is the most widely used method to prevent spam. In this tutorial we shall learn how to generate Captcha image with PHP. In CAPTCHA image verification method an image of text string is displayed over the form to be submitted. Users trying to submit messages have to type that image verification text on a textbox to pass through that process. Human beings can easily read that text from its image, but a robot can't read this text from its image. With deliberate addition of some noise and distortion over the Captcha image makes it even harder to read.

How to generate

To develop spam protection script we need the followings.

  1. A function which can generate a random text string.
  2. A function which can generate an image of definite size of that random text string.
  3. A system which can store that random text such that it can be compared and verified when user submit the form.

Generate random text string:

While generating random text string you should be careful in selection of characters such that they can't raise confusion over the user mind. Such that character 'O' and digit '0', character 'l' and digit '1', looks very much similar and so user can be confused to read the text. Our ultimate goal is to prevent robot in submitting form with minimum loading on the good user. Below, I write a small PHP function which can generate and return a random text.

Code | Download
function random_text()
{
         $str='abcdefghijkmnpqrstuvwxyz23456789';
         $random='';
         $length=6;
         for($i=0; $i<$length; $i++){$random.=$str{rand(0,strlen($str)-1)};}
         return $random;
}

Generate image from text

To generate image with PHP you must have GD library installed on your server. In most of the today's server it is installed by default. Here is a small function which can out-put a jpeg image from a text string directly on the browser window. The size of the image is set as 50px X 16px. You can edit those values according to your need.

Code | Download
function get_image($verification_text)
{

    $img = @imagecreatetruecolor(50, 16)
         or die("Unable to create verification image!");
    $black = imagecolorallocate($img, 0, 0, 0);
    $white = imagecolorallocate($img, 255, 255, 255);
    imagefill($img, 0, 0, $white);
    imagestring($img, 5, 0, 0,  $verification_text, $black);
    imagejpeg($img);
    imagedestroy($img);

}

Storing verification text

In Captcha image verification method you must have a mechanism to store verification text such that it becomes available to the server when user submits the form. Depending upon the situation, you can store it in your server database or as session variable. Even you can save that text as cookie variable, but this method is never safe since cookies are stored at client computer. Below, I write a function which can generate a jpeg image from a random text and store that text as session variable.

Code | Download
<?php
session_start();
$r=random_text();
$_SESSION['verify']=$r;
get_image($r);
function random_text()
{
         $str='abcdefghijkmnpqrstuvwxyz23456789';
         $random='';
         $length=6;
         for($i=0; $i<$length; $i++){$random.=$str{rand(0,strlen($str)-1)};}
         return $random;
}
function get_image($verification_text)
{

    $img = @imagecreatetruecolor(50, 16)
         or die("Unable to create verification image!");
    $black = imagecolorallocate($img, 0, 0, 0);
    $white = imagecolorallocate($img, 255, 255, 255);
    imagefill($img, 0, 0, $white);
    imagestring($img, 5, 0, 0,  $verification_text, $black);
    imagejpeg($img);
    imagedestroy($img);

}
?>

Display image over HTML form

Now you have to display the image out-put from the above PHP script into an HTML form. To do it save the above PHP code in a separate file say captcha.php. To display the image output from captcha.php use one <img> tag whose src property is captcha.php. An example HTML form page code is given below. Take an HTML form page say submit.html and put the following lines of code in it.

Code | Download
<html>
<head>
<title>Example form</title>
</head>
<body>
<h1>Example form</h1>
<form method="post" action="submit.php">
Your name:<input name="name" type="text" style="width:100px;" />
Your email:<input name="email" type="text" style="width:100px;" />
Type text:<input name="verify" type="text" style="width:100px;" />
<img style="border:none" src="captcha.php" />
<input name="submit" type="submit" value="Submit" />
</body></html>

Verify user after submit form

Now we are at the final phase of this tutorial where you verify the Captcha code typed by the user. After submitting form the page will be redirected to the page submit.php where you retrieve the user submitted data from the POST variable. Now compare the catcha code with the stroed SESSION variable and if error found redirect that page back to the submit.html for re-submission.

submit.php
Code | Download
<?php
if((isset($_SESSION['verify'])&&(srtipslashes($_POST['verify'])!=$_SESSION['verify'])){header("Location: submit.html");}
else{
unset($_SESSION['verify']);
//Other PHP code.
//
//
?>
User comments:

Add comment

RAMUI WEBBLOG
HomeAboutContact SitemapTerms of useXMLForum
© 2010,  http://ramui.com   All rights reserved.
Powered by: ramui webblog® Version 1.0