Posted By

ajbatac on 03/18/10


Tagged


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

BrianCoyDesign


Captcha


 / Published in: PHP
 

  1. <?php
  2. class CaptchaSecurityImages {
  3.  
  4. var $font = './monofont.ttf';
  5.  
  6. function generateCode($characters) {
  7. /* list all possible characters, similar looking characters and vowels have been removed */
  8. //$possible = '23456789bcdfghjkmnpqrstvwxyz';
  9. $possible = '1234567890'; // 1st try...
  10. $i = 0;
  11. while ($i < $characters) {
  12. $code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
  13. $i++;
  14. }
  15. return $code;
  16. }
  17.  
  18. function CaptchaSecurityImages($width='100',$height='50',$characters='6') {
  19. $code = $this->generateCode($characters);
  20. /* font size will be 75% of the image height */
  21. $font_size = $height * 0.60;
  22. $image = @imagecreate($width, $height) or die('Cannot Initialize new GD image stream');
  23. /* set the colours */
  24. $background_color = imagecolorallocate($image, 180, 110, 63);
  25. $text_color = imagecolorallocate($image, 120, 50, 10);
  26. $noise_color = imagecolorallocate($image, 255, 150, 102);
  27.  
  28. /* generate random dots in background */
  29. for( $i=0; $i<($width*$height)/3; $i++ ) {
  30. imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color);
  31. }
  32.  
  33. /* generate random lines in background */
  34. for( $i=0; $i<($width*$height)/150; $i++ ) {
  35. imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noise_color);
  36. }
  37.  
  38. /* create textbox and add text */
  39. $textbox = imagettfbbox($font_size, 0, $this->font, $code);
  40. $x = ($width - $textbox[4])/2;
  41. $y = ($height - $textbox[5])/2;
  42.  
  43. imagettftext($image, $font_size, 0, $x, $y, $text_color, $this->font , $code);
  44.  
  45. /* output captcha image to browser */
  46. imagejpeg($image);
  47. imagedestroy($image);
  48. $_SESSION['security_code'] = $code;
  49. }
  50. }
  51.  
  52. $width = isset($_GET['width']) ? $_GET['width'] : '100';
  53. $height = isset($_GET['height']) ? $_GET['height'] : '35';
  54. $characters = isset($_GET['characters']) ? $_GET['characters'] : '3'; //number of characters to show
  55.  
  56. header('Content-Type: image/jpeg');
  57. $captcha = new CaptchaSecurityImages($width,$height,$characters);
  58. ?>

Report this snippet  

You need to login to post a comment.