Captcha Generator using PHP

Language
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.  
  5. include("simple-php-captcha.php");
  6. $_SESSION['captcha'] = simple_php_captcha();
  7.  
  8. ?>
  9. <!DOCTYPE html>
  10.     <title>Example &raquo; 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.  
  18.         img {
  19.             border: solid 1px #ccc;
  20.             margin: 0 2em;
  21.         }
  22.     </style>
  23. </head>
  24.     <h1>
  25.         CAPTCHA Example
  26.     </h1>
  27.     <p>
  28.         <?php
  29.        echo '<img src="' . $_SESSION['captcha']['image_src'] . '" alt="CAPTCHA code">';
  30.  
  31.         ?>
  32.     </p>
  33. </body>
  34. </html>

Create simple-php-captcha.php

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

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Add new comment