Your Ad Here

Posted By

stz184 on 10/17/10


Tagged

Captcha


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

pytheas
HelloKit
czehner


Captcha with arithmetic's questions


 / Published in: PHP
 

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/fontdetails.html?fontid=2939

  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. imagedestroy($im);
  46.  
  47. //usage : save this snippet as captcha.php file and use it that
  48. //point it as image source
  49. //<img src="captcha.php" />
  50. //to check is it passed correctly, do following
  51. //if(isset($_SESSION['code']) && ($_POST['captcha'] == $_SESSION['code']))
  52. //its needed to check is $_SESSION['code'] is set, because if somebody block
  53. //the image loading, the check ($_POST['captcha'] == $_SESSION['code']) will
  54. //return false positive if the form is sent with empty captcha field

Report this snippet  

You need to login to post a comment.