<?php
//Start the session so we can store what the code actually is.
session_start();
$font = 'frhnd575.ttf'; //replace this with own font .ttf
//Now let's use md5 to generate a totally random string
/*
$md5 = strtoupper(md5(microtime() * mktime()));
We dont need a 32 character long string so we trim it down to 5
$string1 = substr($md5,0,8);
*/
$lenght=6;
$char_to_use='123456789';
for($i=0; $i < $lenght; $i++){
$do=mt_rand(0, strlen($char_to_use)-1);
$string=$string . $char_to_use{$do};
}
/*
Now for the GD stuff, for ease of use lets create
the image from a background image.
*/
$captcha = imagecreatefromjpeg("captcha.jpg"); create an image named "captcha.jpg" in the same directory
/*
Lets set the colours, the colour $line is used to generate lines.
Using a blue misty colours. The colour codes are in RGB
*/
$black = imagecolorallocate($captcha, 0, 0, 255);
$line = imagecolorallocate($captcha,0,0,0);
/*
Now to make it a little bit harder for any bots to break,
assuming they can break it so far. Lets add some lines
in (static lines) to attempt to make the bots life a little harder
*/
imageline($captcha,0,0,39,43,$line);
imageline($captcha,40,0,64,43,$line);
imageline($captcha,70,0,100,43,$line);
imageline($captcha,100,6,0,43,$line);
/*
Now for the all important writing of the randomly generated string to the image.
*/
imagettftext($captcha, 30, 0, 8, 30, $black, $font, $string);
/*
Encrypt and store the key inside of a session
*/
$_SESSION['key'] = md5($string);
/*
Output the image
*/
header("Content-type: image/png");
imagepng($captcha);
?>
Save the above code as captcha.php and call it like
<img src="captcha.php" /> <input type="text" name="cap" />
Then, when form is submitted
<?
$cap = md5($_POST['cap']);
if(!strcasecmp($cap, $_SESSION['key']) == 0):
echo "<font color=\"#FF0000\">* Sorry, your image verification was wrong!</font>";
?>
Your comments will be highly welcomed.