Return to Snippet

Revision: 34084
at October 17, 2010 02:33 by stz184


Initial Code
session_start();
header("Content-type: image/png");
$width = 120;
$height = 30;
$im = @imagecreate($width, $height)
    or die("Cannot Initialize new GD image stream");
imagecolorallocate($im, 247, 250, 233);
$noise_color = imagecolorallocate($im, 253, 175, 90);
	for( $i=0; $i<($width*$height)/3; $i++ ) {
         imagefilledellipse($im, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color);
      }
      /* generate random lines in background */
      for( $i=0; $i<($width*$height)/120; $i++ ) {
         imageline($im, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noise_color);
      }
$text_color = imagecolorallocate($im, 175, 102, 43);


$action = array('+', '*', '-');
shuffle($action);
if($action[0] == '+') {
	$a = rand(1, 9);
	$b = rand(1, 9);
	$_SESSION['code'] = $a + $b;
}
elseif($action[0] == '*') {
	$a = rand(1, 9);
	$b = rand(1, 9);
	$_SESSION['code'] = $a * $b;
}
elseif($action[0] == '-') {
	$b = rand(1, 9);
	$c = $b+1;
	$a = rand($c, 9);
	
	$_SESSION['code'] = $a - $b;
}

$text = $a.$action[0].$b;

for($j = 0; $j < strlen($text); $j++) {
	$angle = rand(-20, 20);
	imagettftext($im, 18, $angle, 29+($j*23), (18+(($height-18)/2)), $text_color, './WC_Wunderbach_Rough.ttf', $text[$j] );
}
imagepng($im);
imagedestroy($im);

//usage : save this snippet as captcha.php file and use it that
//point it as image source 
//<img src="captcha.php" />
//to check is it passed correctly, do following
//if(isset($_SESSION['code']) && ($_POST['captcha'] == $_SESSION['code'])) 
//its needed to check is $_SESSION['code'] is set, because if somebody block
//the image loading, the check ($_POST['captcha'] == $_SESSION['code']) will 
//return false positive if the form is sent with empty captcha field

Initial URL


Initial Description
Save this snippet as .php file and use it as image source.
This captcha code shows random arithmetic's questions.
You can download needed font from http://www.1001fonts.com/font_details.html?font_id=2939

Initial Title
Captcha with arithmetic's questions

Initial Tags


Initial Language
PHP