PHP Image Code Verification

If you’ve got a website with a form of any type, a user can easily abuse this form with a program that submits the form repeatedly. Using the power of PHP you can have your form generate a unique image every time that the user has to enter the text into the form. Below I’ll explain how to do it.

Setting up the form page
The form, form processor, and image script all need to be able to access the root code number. This number will then be put through an encryption routine to create the code that must be entered. We will do this by creating a session variable, and assigning a random number to it. We will do this on the form page below.

<?php
session_start();
session_register('sessioncode');
$sessioncode = rand(12345, 99999);
?>
<FORM METHOD=POST ACTION="processor.php">
Comment: <INPUT TYPE=TEXT NAME="comment"><BR>
Code: <INPUT TYPE=TEXT NAME="code"> <IMG SRC="image.php"><BR>
<INPUT TYPE=TEXT NAME="submit" VALUE="Submit"></FORM>

Generating the image
The image will be generated by encrypting the code with MD5 and a unique string for your form. It will also be cut off after 6 characters, and will be in all uppercase. The code is below.

<?php
session_start();
session_register('sessioncode');
$im = imagecreate(55, 15);
$bg = imagecolorallocate($im, 255, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 255);
imagecolortransparent($im, $bg);
imagestring($im, 5, 0, 0, substr(strtoupper(md5("Mytext".$sessioncode)), 0,6), $textcolor);
imagepng($im);
exit();
?>

Verifying the code
Verifying the code is simple. Just uppercase the input from the user, and verify it by the encrypted code again like below.

<?php
session_start();
session_register('sessioncode');
if (strtoupper($code) == substr(strtoupper(md5("Mytext".$sessioncode)), 0,6)) {
   echo "Good job";
} else {
   echo "Bad job entering the code";
}
?>

So there you go. You can now generate a php verification image and check the code against the user’s typing. You can get more advanced by adding random pixels and lines to the image to make it difficult for programs to be able to extract the text from the image.

One thought to “PHP Image Code Verification”

Comments are closed.