Captcha image

As a means to stop the spam in the guestbook I have created a captcha image code.

captcha.php

<?php
// Font selection
$font = './verdana.ttf';
 
session_start();
 
// Generation of random numbers
$randomnr = rand(100, 999);
$randomnr1 = rand(1, 9);
$randomnr2 = rand(1, 9);
$randomnr3 = rand(1, 9);
 
// Saving the encrypted code 
$_SESSION['randomnr'] = md5($randomnr1*100+$randomnr2*10+$randomnr3);
 
// Creating the captcha image
$im = imagecreatetruecolor(72, 35);
 
// Setting up the colors
$line = imagecolorallocate($im, 43, 111, 134);
$grey = imagecolorallocate($im, 128, 128, 128);
$white = imagecolorallocate($im, 255, 255, 255);
$color[0] = imagecolorallocate($im, 237, 28, 36);	//Red
$color[1] = imagecolorallocate($im, 168, 230, 29); 	//Green
$color[2] = imagecolorallocate($im, 77, 109, 243);	//Blue
 
imagefilledrectangle($im, 0, 0, 72, 35, $white);
 
// Adding the random background numbers
for($i=5;$i<=65;$i=$i+20){
  imagettftext($im, 10, 45, $i, 26, $grey, $font, $randomnr);
}
 
// Adding the vertical lines
for($i=5;$i<72;$i=$i+10){
  imageline($im,$i,0,$i,35,$line);
}
 
// Adding the horizontal lines
for($i=5;$i<35;$i=$i+10){
  imageline($im,0,$i,72,$i,$line);
}
 
// Adding the actual captcha code with random colors
imagettftext($im, 25, 0, 5, 30, $color[rand(0, 2)], $font, $randomnr1);
imagettftext($im, 25, 0, 28, 30, $color[rand(0, 2)], $font, $randomnr2);
imagettftext($im, 25, 0, 51, 30, $color[rand(0, 2)], $font, $randomnr3);
 
// Prevent caching
header("Expires: Wed, 1 Jan 1997 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
 
// Output image
header ("Content-type: image/png");
imagepng($im);
imagedestroy($im);
?>

result

Download

You can download captcha.php here: captch.php (1.9 kB)

dokuwiki/captcha.txt · Last modified: 2008/06/10 22:04 by marc
Creative Commons License Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0