Creating animated CAPTCHA

written by Arief Bayu Purwanto on February 13, 2007 in Tutorial with 3 comments

Let’s learn how to create CAPTCHA, but not just plain. We’ll build an animated captcha. So, how do we create it? First we need GIFEncoder class from phpclasses.

require_once "GIFEncoder.class.php";


This class will create new GIF image based on multiple image we supply. Next we need to create a temporary folder to store our single image, before compiled into animated captcha. Set image width and height also how long the loop is.

$TEMP_FOLDER = 'D:/documents/bayu/work/Scriptlance/ticker/captchaGIF/tmp';
$imgheight = 30;
$imgwidth = 60;
$loop = $imgwidth / 2;

Now, lets create the captcha text and store it in session.

$rnd = rand(0, 1000000);
$text = strtoupper(substr(md5( microtime() * $rnd),1,5));
$_SESSION['CAPTCHA_TEXT'] = $text;

My idea here is to create the text using md5. You can use another way if you like. Next step, we’ll create our single image that need to be compiled.

for($i = 1; $i <= $loop; $i++){
$im = @imagecreate($imgwidth, $imgheight)
or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im, 0, 0, 0);
$text_color = imagecolorallocate($im, 255, 255, 255);
$green = imagecolorallocate($im, 0, 0, 0);
imagestring($im, 5, 10, 5, $text, $text_color);
imagefilledrectangle($im,1,1,($i - 1) * 2,$imgheight, $green);
imagefilledrectangle($im,($i - 1) * 2 + 8,1,$imgwidth,$imgheight, $green);
$fname = $TEMP_FOLDER . '/' . $rnd . '-' . $i . '.gif';
imagegif($im, $fname);
$frames[] = $fname;
$framed[] = 1;
$frames[] = $fname;
$framed[] = 1;
imagedestroy($im);
}

Now that we have our image, we just need to compile it into single gif animation and send it into browser.

$gif = new GIFEncoder (
$frames,
$framed,
0,
2,
0, 0, 0,
'C_FILE'
);
Header ( 'Content-type:image/gif' );
echo $gif->GetAnimation ( );

That’s it we’ve finished our image. But wait, we’ll leave so much trashes on our temporary folder. So, we need to create function fo clear that temp folder and call this function right after initializing GIFEncoder class or before header() call.

function clear_files($number, $loop){
global $TEMP_FOLDER;
for($i = 1; $i <= $loop; $i++){
$thefile = $TEMP_FOLDER . '/' . $number . '-' . $i . '.gif';
unlink($thefile);
}
}

Follow this link if you want to see the demo. Here‘s the download link, if you want to customize.