PHP - Turing test

Turing test is a small image with random text which user should enter in order to process his further requests. It is based on presumption that text on image could be recognized only by humans. This is the reason why you will find these images very distorted. Basically, web server will create image background, simple text and apply image distortion with mathematical function. This way, web server makes impossible to use OCR software to recognize text on the image.

Turing test should ensure web server that on the other side of a connection is a human. This is good when you want to give more security to your system. It is common practice to insert Turing test in login or registration forms. This way you will disable automatic use of your web forms. If on the other side of a connection is a malicious user who wants to break security, he is extremely slowed down, because he can not use software for automated exploiting or breaking security (eg software for brute force password guessing).

Script will create random text, save it to a user session, and output generated image.
When user posts web forms, you should check $_SESSION['TuringTest'] against strtoupper($_REQUEST['TuringTest']), and if they are the same, test is passed.

turing.php
<php
list($usec, $sec) = explode(" ", microtime());
srand((float)$usec + (float)$sec * 1000000);
$string = md5(rand(0,9999));
$code_string = strtoupper(substr($string, rand(0,26), 5));
session_start();
$_SESSION['TuringTest'] = $code_string;
session_write_close();
$im = imagecreate(61,25);
$color_back = imagecolorallocate($im, 255,255,255);
imagefill($im, 0, 0, $color_back);
$text_color = imagecolorallocate($im, 225,0,0);
imagettftext($im, 13, 0, 3, 19, $text_color, "Arial.ttf", $code_string);
// if your server does not support TTF fonts, use this snippet
// instead of upper line
// for ($i=0, $x=7; $i < strlen($code_string); $i++, $x+=10) // imagechar($im, 5, $x, 4, $code_string[$i], 123456); $color_line = imagecolorallocate($im, rand(0,225), rand(0,225), rand(0,225)); for($i=0;$i<=24;$i+=8) imageline ($im,0,$i,80,$i,$color_line); for($i=0;$i<=60;$i+=6) imageline ($im,$i,0,$i,30,$color_line); header("Content-type: image/jpeg"); imagejpeg($im); imagedestroy($im); ?> form.php
This is a script you can use to test turing.php. It is a simple web form which asks you to insert security code.

if (isset($_REQUEST['TuringTest']))
{
session_start();
if (strtoupper($_REQUEST['TuringTest']) == $_SESSION['TuringTest'])
$Message = 'Touring test passed';
else
$Message = 'Turing test NOT passed';
session_destroy();
}