Simple image CAPTCHA


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

In img tag set src=\"captcha.php\"


Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. function create_captcha($char_count = 6)
  4. {
  5. $possible = '23456789bcdfghjkmnpqrstvwxyz';
  6. $security_code = '';
  7. $i = 0;
  8. while ($i < $char_count) {
  9. $security_code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
  10. $i++;
  11. }
  12.  
  13. //Set the session to store the security code
  14. $_SESSION["captcha_code"] = $security_code;
  15.  
  16. $width = 100;
  17. $height = 25;
  18.  
  19. //Create the image resource
  20. $image = ImageCreate($width, $height);
  21.  
  22. //We are making three colors, white, black and gray
  23. $white = ImageColorAllocate($image, 255, 255, 255);
  24. $black = ImageColorAllocate($image, 0, 0, 0);
  25. $grey = ImageColorAllocate($image, 204, 204, 204);
  26.  
  27. //Make the background black
  28. ImageFill($image, 0, 0, $black);
  29.  
  30. //Add randomly generated string in white to the image
  31. ImageString($image, 5, 30, 3, $security_code, $white);
  32.  
  33. //Throw in some lines to make it a little bit harder for any bots to break
  34. ImageRectangle($image,0,0,$width-1,$height-1,$grey);
  35. imageline($image, 0, 5, $width, 5, $grey);
  36. imageline($image, $width/4, 0, $width/2, $height, $grey);
  37. imageline($image, 0, 18, $width, 18, $grey);
  38. imageline($image, 46, 0, 86, $height, $grey);
  39.  
  40. header("Content-Type: image/jpeg");
  41.  
  42. //Output the newly created image in jpeg format
  43. ImageJpeg($image);
  44.  
  45. //Free up resources
  46. ImageDestroy($image);
  47. }
  48.  
  49. create_captcha();
  50.  
  51. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.