CAPTCHA image using PHP

To create a image form validation system we will firstly need to create the image.

header('Content-type: image/png');
session_start();

We have set the file type to image/png and we will return image data to display on a page.

function random_string($num)
{
   $string = 'ABCDEFGHIJKLMNPQRSTUVWXYZ123456789';
   $return = '';
   while($num-- > 0)
      $return .= $string[rand(0, strlen($string) - 1)];
   return $return;
}

This function will return a random subset of characters from the string defined within the function.

$text = random_string(8);
$_SESSION['NUM'] = sha1($text);

Now that we have a random string we can add the value to a session so that when a user enters the characters we can check them against the value calculated.

$image = @imagecreatefrompng('image.png');
$text_color = @imagecolorallocate($image, 0, 0, 0);

A predefined image has been made with a background that the characters will be entered into (the example image is 200px in height and 100px in width). The variable $text_color holds the colour black that we will use to colour the text.

for($i = 0; $i < strlen($text); $i++)
   @imagestring($image, 5, 35 + ($i*10), round(rand(10,30)), $text[$i], $text_color);

This loop adds the characters to the image loaded earlier, the padding between each character is constant but the height of each character varies randomly.

@imagepng($image);
@imagedestroy($image);

We finally output the image data.

The form now needs to be made that will allow the user to type in the characters that we have displayed in the image.

(Ignore any spaces)
<img src="test2.php" width="200" height="100" />
<form id="form1" name="form1" method="post" action="#">
   <input type="text" name="image" id="image" />
   <input type="submit" name="submit" id="submit" value="submit">
</form>

A field is provided that allows the user to type the text and a submit button is provided. We finally need to check what the user has typed in against that stored in the session. Note the address of the image, it points to the code we made earlier that returns image data.

session_start();
if($_POST['submit'])
{
   if(sha1(str_replace(' ', '', $_POST['image'])) == $_SESSION['NUM'])
      echo 'Input correct.';
   else
      echo 'Input incorrect.';
}

A simple check is done against the value in the session and a message is displayed to the user.

Downloads

Categories

Tags

No tags

Social