Captcha Generator PHP Script


Captcha Generator PHP Script.

In this tutorial we are going to learn how to make a captcha generator that you can use in login, sign up, comment and etc. Just download the source code below.

 

DIRECTIONS

Create index.php

 
 
  1. <?php
  2. session_start();
  3. $_SESSION = array();
  4. include("simple-php-captcha.php");
  5. $_SESSION['captcha'] = simple_php_captcha();
  6. ?>
  7. <!DOCTYPE html>
  8. <html>
  9. <head>
  10. <title>Example » A simple PHP CAPTCHA script</title>
  11. <style type="text/css">
  12. pre {
  13. border: solid 1px #bbb;
  14. padding: 10px;
  15. margin: 2em;
  16. }
  17. img {
  18. border: solid 1px #ccc;
  19. margin: 0 2em;
  20. }
  21. </style>
  22. </head>
  23. <body>
  24. <h1>
  25. CAPTCHA Example
  26. </h1>
  27. <p>
  28. <?php
  29. echo '<img src="' . $_SESSION['captcha']['image_src'] . '" alt="CAPTCHA code">';
  30. ?>
  31. </p>
  32. </body>
  33. </html>

 

Create simple-php-captcha.php

 

Code:
 
  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&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&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. unset($_SESSION['_CAPTCHA']);
  104. // Pick random background, get info, and start captcha
  105. $background = $captcha_config['backgrounds'][mt_rand(0, count($captcha_config['backgrounds']) -1)];
  106. list($bg_width, $bg_height, $bg_type, $bg_attr) = getimagesize($background);
  107. $captcha = imagecreatefrompng($background);
  108. $color = hex2rgb($captcha_config['color']);
  109. $color = imagecolorallocate($captcha, $color['r'], $color['g'], $color['b']);
  110. // Determine text angle
  111. $angle = mt_rand( $captcha_config['angle_min'], $captcha_config['angle_max'] ) * (mt_rand(0, 1) == 1 ? -1 : 1);
  112. // Select font randomly
  113. $font = $captcha_config['fonts'][mt_rand(0, count($captcha_config['fonts']) - 1)];
  114. // Verify font file exists
  115. if( !file_exists($font) ) throw new Exception('Font file not found: ' . $font);
  116. //Set the font size.
  117. $font_size = mt_rand($captcha_config['min_font_size'], $captcha_config['max_font_size']);
  118. $text_box_size = imagettfbbox($font_size, $angle, $font, $captcha_config['code']);
  119. // Determine text position
  120. $box_width = abs($text_box_size[6] - $text_box_size[2]);
  121. $box_height = abs($text_box_size[5] - $text_box_size[1]);
  122. $text_pos_x_min = 0;
  123. $text_pos_x_max = ($bg_width) - ($box_width);
  124. $text_pos_x = mt_rand($text_pos_x_min, $text_pos_x_max);
  125. $text_pos_y_min = $box_height;
  126. $text_pos_y_max = ($bg_height) - ($box_height / 2);
  127. if ($text_pos_y_min > $text_pos_y_max) {
  128. $temp_text_pos_y = $text_pos_y_min;
  129. $text_pos_y_min = $text_pos_y_max;
  130. $text_pos_y_max = $temp_text_pos_y;
  131. }
  132. $text_pos_y = mt_rand($text_pos_y_min, $text_pos_y_max);
  133. // Draw shadow
  134. if( $captcha_config['shadow'] ){
  135. $shadow_color = hex2rgb($captcha_config['shadow_color']);
  136. $shadow_color = imagecolorallocate($captcha, $shadow_color['r'], $shadow_color['g'], $shadow_color['b']);
  137. 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']);
  138. }
  139. // Draw text
  140. imagettftext($captcha, $font_size, $angle, $text_pos_x, $text_pos_y, $color, $font, $captcha_config['code']);
  141. // Output image
  142. header("Content-type: image/png");
  143. imagepng($captcha);
  144. }

 

Thank you for viewing this article. If you have any comments, suggestions, questions just comment below or email me at [email protected]

 

 

Have any Question or Comment?

Leave a Reply

Your email address will not be published. Required fields are marked *

"