Captcha with arithmetic's questions


/ Published in: PHP
Save to your folder(s)

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


Copy this code and paste it in your HTML
  1. header("Content-type: image/png");
  2. $width = 120;
  3. $height = 30;
  4. $im = @imagecreate($width, $height)
  5. or die("Cannot Initialize new GD image stream");
  6. imagecolorallocate($im, 247, 250, 233);
  7. $noise_color = imagecolorallocate($im, 253, 175, 90);
  8. for( $i=0; $i<($width*$height)/3; $i++ ) {
  9. imagefilledellipse($im, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color);
  10. }
  11. /* generate random lines in background */
  12. for( $i=0; $i<($width*$height)/120; $i++ ) {
  13. imageline($im, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noise_color);
  14. }
  15. $text_color = imagecolorallocate($im, 175, 102, 43);
  16.  
  17.  
  18. $action = array('+', '*', '-');
  19. shuffle($action);
  20. if($action[0] == '+') {
  21. $a = rand(1, 9);
  22. $b = rand(1, 9);
  23. $_SESSION['code'] = $a + $b;
  24. }
  25. elseif($action[0] == '*') {
  26. $a = rand(1, 9);
  27. $b = rand(1, 9);
  28. $_SESSION['code'] = $a * $b;
  29. }
  30. elseif($action[0] == '-') {
  31. $b = rand(1, 9);
  32. $c = $b+1;
  33. $a = rand($c, 9);
  34.  
  35. $_SESSION['code'] = $a - $b;
  36. }
  37.  
  38. $text = $a.$action[0].$b;
  39.  
  40. for($j = 0; $j < strlen($text); $j++) {
  41. $angle = rand(-20, 20);
  42. imagettftext($im, 18, $angle, 29+($j*23), (18+(($height-18)/2)), $text_color, './WC_Wunderbach_Rough.ttf', $text[$j] );
  43. }
  44. imagepng($im);
  45.  
  46. //usage : save this snippet as captcha.php file and use it that
  47. //point it as image source
  48. //<img src="captcha.php" />
  49. //to check is it passed correctly, do following
  50. //if(isset($_SESSION['code']) && ($_POST['captcha'] == $_SESSION['code']))
  51. //its needed to check is $_SESSION['code'] is set, because if somebody block
  52. //the image loading, the check ($_POST['captcha'] == $_SESSION['code']) will
  53. //return false positive if the form is sent with empty captcha field

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.