PageRenderTime 44ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/simple-php-captcha.php

http://github.com/claviska/simple-php-captcha
PHP | 176 lines | 125 code | 28 blank | 23 comment | 24 complexity | e556db9465815878c93c97ebda0c9265 MD5 | raw file
  1. <?php
  2. //
  3. // A simple PHP CAPTCHA script
  4. //
  5. // Copyright 2011 by Cory LaViska for A Beautiful Site, LLC
  6. //
  7. // See readme.md for usage, demo, and licensing info
  8. //
  9. function simple_php_captcha($config = array()) {
  10. // Check for GD library
  11. if( !function_exists('gd_info') ) {
  12. throw new Exception('Required GD library is missing');
  13. }
  14. $bg_path = dirname(__FILE__) . '/backgrounds/';
  15. $font_path = dirname(__FILE__) . '/fonts/';
  16. // Default values
  17. $captcha_config = array(
  18. 'code' => '',
  19. 'min_length' => 5,
  20. 'max_length' => 5,
  21. 'backgrounds' => array(
  22. $bg_path . '45-degree-fabric.png',
  23. $bg_path . 'cloth-alike.png',
  24. $bg_path . 'grey-sandbag.png',
  25. $bg_path . 'kinda-jean.png',
  26. $bg_path . 'polyester-lite.png',
  27. $bg_path . 'stitched-wool.png',
  28. $bg_path . 'white-carbon.png',
  29. $bg_path . 'white-wave.png'
  30. ),
  31. 'fonts' => array(
  32. $font_path . 'times_new_yorker.ttf'
  33. ),
  34. 'characters' => 'ABCDEFGHJKLMNPRSTUVWXYZabcdefghjkmnprstuvwxyz23456789',
  35. 'min_font_size' => 28,
  36. 'max_font_size' => 28,
  37. 'color' => '#666',
  38. 'angle_min' => 0,
  39. 'angle_max' => 10,
  40. 'shadow' => true,
  41. 'shadow_color' => '#fff',
  42. 'shadow_offset_x' => -1,
  43. 'shadow_offset_y' => 1
  44. );
  45. // Overwrite defaults with custom config values
  46. if( is_array($config) ) {
  47. foreach( $config as $key => $value ) $captcha_config[$key] = $value;
  48. }
  49. // Restrict certain values
  50. if( $captcha_config['min_length'] < 1 ) $captcha_config['min_length'] = 1;
  51. if( $captcha_config['angle_min'] < 0 ) $captcha_config['angle_min'] = 0;
  52. if( $captcha_config['angle_max'] > 10 ) $captcha_config['angle_max'] = 10;
  53. if( $captcha_config['angle_max'] < $captcha_config['angle_min'] ) $captcha_config['angle_max'] = $captcha_config['angle_min'];
  54. if( $captcha_config['min_font_size'] < 10 ) $captcha_config['min_font_size'] = 10;
  55. if( $captcha_config['max_font_size'] < $captcha_config['min_font_size'] ) $captcha_config['max_font_size'] = $captcha_config['min_font_size'];
  56. // Generate CAPTCHA code if not set by user
  57. if( empty($captcha_config['code']) ) {
  58. $captcha_config['code'] = '';
  59. $length = mt_rand($captcha_config['min_length'], $captcha_config['max_length']);
  60. while( strlen($captcha_config['code']) < $length ) {
  61. $captcha_config['code'] .= substr($captcha_config['characters'], mt_rand() % (strlen($captcha_config['characters'])), 1);
  62. }
  63. }
  64. // Generate HTML for image src
  65. if ( strpos($_SERVER['SCRIPT_FILENAME'], $_SERVER['DOCUMENT_ROOT']) ) {
  66. $image_src = substr(__FILE__, strlen( realpath($_SERVER['DOCUMENT_ROOT']) )) . '?_CAPTCHA&amp;t=' . urlencode(microtime());
  67. $image_src = '/' . ltrim(preg_replace('/\\\\/', '/', $image_src), '/');
  68. } else {
  69. $_SERVER['WEB_ROOT'] = str_replace($_SERVER['SCRIPT_NAME'], '', $_SERVER['SCRIPT_FILENAME']);
  70. $image_src = substr(__FILE__, strlen( realpath($_SERVER['WEB_ROOT']) )) . '?_CAPTCHA&amp;t=' . urlencode(microtime());
  71. $image_src = '/' . ltrim(preg_replace('/\\\\/', '/', $image_src), '/');
  72. }
  73. $_SESSION['_CAPTCHA']['config'] = serialize($captcha_config);
  74. return array(
  75. 'code' => $captcha_config['code'],
  76. 'image_src' => $image_src
  77. );
  78. }
  79. if( !function_exists('hex2rgb') ) {
  80. function hex2rgb($hex_str, $return_string = false, $separator = ',') {
  81. $hex_str = preg_replace("/[^0-9A-Fa-f]/", '', $hex_str); // Gets a proper hex string
  82. $rgb_array = array();
  83. if( strlen($hex_str) == 6 ) {
  84. $color_val = hexdec($hex_str);
  85. $rgb_array['r'] = 0xFF & ($color_val >> 0x10);
  86. $rgb_array['g'] = 0xFF & ($color_val >> 0x8);
  87. $rgb_array['b'] = 0xFF & $color_val;
  88. } elseif( strlen($hex_str) == 3 ) {
  89. $rgb_array['r'] = hexdec(str_repeat(substr($hex_str, 0, 1), 2));
  90. $rgb_array['g'] = hexdec(str_repeat(substr($hex_str, 1, 1), 2));
  91. $rgb_array['b'] = hexdec(str_repeat(substr($hex_str, 2, 1), 2));
  92. } else {
  93. return false;
  94. }
  95. return $return_string ? implode($separator, $rgb_array) : $rgb_array;
  96. }
  97. }
  98. // Draw the image
  99. if( isset($_GET['_CAPTCHA']) ) {
  100. session_start();
  101. $captcha_config = unserialize($_SESSION['_CAPTCHA']['config']);
  102. if( !$captcha_config ) exit();
  103. if( isset($_GET['_RENDER']) ) {
  104. $_SESSION['_CAPTCHA'] = simple_php_captcha();
  105. } else {
  106. unset($_SESSION['_CAPTCHA']);
  107. }
  108. // Pick random background, get info, and start captcha
  109. $background = $captcha_config['backgrounds'][mt_rand(0, count($captcha_config['backgrounds']) -1)];
  110. list($bg_width, $bg_height, $bg_type, $bg_attr) = getimagesize($background);
  111. $captcha = imagecreatefrompng($background);
  112. $color = hex2rgb($captcha_config['color']);
  113. $color = imagecolorallocate($captcha, $color['r'], $color['g'], $color['b']);
  114. // Determine text angle
  115. $angle = mt_rand( $captcha_config['angle_min'], $captcha_config['angle_max'] ) * (mt_rand(0, 1) == 1 ? -1 : 1);
  116. // Select font randomly
  117. $font = $captcha_config['fonts'][mt_rand(0, count($captcha_config['fonts']) - 1)];
  118. // Verify font file exists
  119. if( !file_exists($font) ) throw new Exception('Font file not found: ' . $font);
  120. //Set the font size.
  121. $font_size = mt_rand($captcha_config['min_font_size'], $captcha_config['max_font_size']);
  122. $text_box_size = imagettfbbox($font_size, $angle, $font, $captcha_config['code']);
  123. // Determine text position
  124. $box_width = abs($text_box_size[6] - $text_box_size[2]);
  125. $box_height = abs($text_box_size[5] - $text_box_size[1]);
  126. $text_pos_x_min = 0;
  127. $text_pos_x_max = ($bg_width) - ($box_width);
  128. $text_pos_x = mt_rand($text_pos_x_min, $text_pos_x_max);
  129. $text_pos_y_min = $box_height;
  130. $text_pos_y_max = ($bg_height) - ($box_height / 2);
  131. if ($text_pos_y_min > $text_pos_y_max) {
  132. $temp_text_pos_y = $text_pos_y_min;
  133. $text_pos_y_min = $text_pos_y_max;
  134. $text_pos_y_max = $temp_text_pos_y;
  135. }
  136. $text_pos_y = mt_rand($text_pos_y_min, $text_pos_y_max);
  137. // Draw shadow
  138. if( $captcha_config['shadow'] ){
  139. $shadow_color = hex2rgb($captcha_config['shadow_color']);
  140. $shadow_color = imagecolorallocate($captcha, $shadow_color['r'], $shadow_color['g'], $shadow_color['b']);
  141. imagettftext($captcha, $font_size, $angle, $text_pos_x + $captcha_config['shadow_offset_x'], $text_pos_y + $captcha_config['shadow_offset_y'], $shadow_color, $font, $captcha_config['code']);
  142. }
  143. // Draw text
  144. imagettftext($captcha, $font_size, $angle, $text_pos_x, $text_pos_y, $color, $font, $captcha_config['code']);
  145. // Output image
  146. header("Content-type: image/png");
  147. imagepng($captcha);
  148. }