Articles: Image verification

Kristian Fiskerstrand's blog

Many, including me are constantly flooded by bots automatically submitting forms hoping to achieve advertising. To reduce this problem it is often benificial to add some form of authentification token at random that is hard for bots to read. In my case I choose an image to do this.
Added: 2005-08-27 15:24:57 - Modified: 2006-06-02 17:49:32 - Level: Beginner
Printer friendly version PDF File
Recommend this article to a friend.

Bookmark this on google Bookmark this on del.icio.us Submit this to digg Bookmark this at yahoo Bookmark this at reddit Bookmark this at furl Search technorati for links to this page Toggle more

The approach is very simple.

  1. You generate a random string
  2. You save it in a session variable
  3. You show it in an image
  4. User read the image and write the string in a form input
  5. You match the user input with the session variable

This counter the bot-problem in most cases. To generate the authentification input you can use a number of methods, personally I', fond of using hashes of some sort, the downside of this is that you will only get hexadecimal output. If you want it more random, you can use a generator of your own outputting any char you want.

The page containing the form include this source

session_start();
$_SESSION['val_text']=substr(sha1(rand()),0,5);

You then include <img src="/formvalid_img.php" alt="validation picture" />

The formvalid_img.php file look like this

session_start();
$font = "/usr/local/ttf/verdana.ttf";
$size = 20;
$text = $_SESSION['val_text'];

$im = imagecreatefrompng("images/noiseimage.png");
$white = imagecolorallocate($im, 255,255,255);
$black = imagecolorallocate($im, 0,0,0);
// Display the image
header("Content-type: image/png");
imagettftext($im, $size, 0, 35, $size+15, $black, $font, $text);
imagepng($im);
imagedestroy($im);
?>

The image file I use for a noisy background can be found at http://www.kfwebs.net/images/noiseimage.png, and you will have to modify the script appropriately according to location to your files.

The result is something like:

Image validation example

In the form-processing file you can do something like

if($_SESSION['val_text']!=$_POST['valid'] || !isset($_POST['valid']) || $_POST['valid']=="")
{
echo "Image validation did not match";
}
else
{
// Do whatever you want
}

If you don't have FreeType installed you can use imagestring($im,3,50,25,$text,$black); instead

Related articles:



[Sitemap]