Integrate Simple PHP CAPTCHA On Form

Everytime you see your database with some spam data which eating your database then you must apply captcha validation on public form which prevent span entry as a server side validation. By using few tricks anybody can disable or manipulate client side captcha validation if you want to make your registration or any public form full proof then you must apply server side captcha validation to prevent spam entry. So in this post I am going to share free simple php script to integrate cpatcha validation on your form quickly.
PHP Captcha

Here is the function for creating cpatcha image in PHP.

<?php







function simple_php_captcha($config = array()) {
    
    if( !function_exists('gd_info') ) {
        throw new Exception('Required GD library is missing');
    }
    $bg_path = dirname(__FILE__) . '/backgrounds/';
    $font_path = dirname(__FILE__) . '/fonts/';
    
    $captcha_config = array(
        'code' => '',
        'min_length' => 5,
        'max_length' => 5,
        'backgrounds' => array(
            $bg_path . '45-degree-fabric.png',
            $bg_path . 'cloth-alike.png',
            $bg_path . 'grey-sandbag.png',
            $bg_path . 'kinda-jean.png',
            $bg_path . 'polyester-lite.png',
            $bg_path . 'stitched-wool.png',
            $bg_path . 'white-carbon.png',
            $bg_path . 'white-wave.png'
        ),
        'fonts' => array(
            $font_path . 'times_new_yorker.ttf'
        ),
        'characters' => 'ABCDEFGHJKLMNPRSTUVWXYZabcdefghjkmnprstuvwxyz23456789',
        'min_font_size' => 28,
        'max_font_size' => 28,
        'color' => '#666',
        'angle_min' => 0,
        'angle_max' => 10,
        'shadow' => true,
        'shadow_color' => '#fff',
        'shadow_offset_x' => -1,
        'shadow_offset_y' => 1
    );
    
    if( is_array($config) ) {
        foreach( $config as $key => $value ) $captcha_config[$key] = $value;
    }
    
    if( $captcha_config['min_length'] < 1 ) $captcha_config['min_length'] = 1;
    if( $captcha_config['angle_min'] < 0 ) $captcha_config['angle_min'] = 0;
    if( $captcha_config['angle_max'] > 10 ) $captcha_config['angle_max'] = 10;
    if( $captcha_config['angle_max'] < $captcha_config['angle_min'] ) $captcha_config['angle_max'] = $captcha_config['angle_min'];
    if( $captcha_config['min_font_size'] < 10 ) $captcha_config['min_font_size'] = 10;
    if( $captcha_config['max_font_size'] < $captcha_config['min_font_size'] ) $captcha_config['max_font_size'] = $captcha_config['min_font_size'];
    
    if( empty($captcha_config['code']) ) {
        $captcha_config['code'] = '';
        $length = mt_rand($captcha_config['min_length'], $captcha_config['max_length']);
        while( strlen($captcha_config['code']) < $length ) {
            $captcha_config['code'] .= substr($captcha_config['characters'], mt_rand() % (strlen($captcha_config['characters'])), 1);
        }
    }
    
    if ( strpos($_SERVER['SCRIPT_FILENAME'], $_SERVER['DOCUMENT_ROOT']) ) {
        $image_src = substr(__FILE__, strlen( realpath($_SERVER['DOCUMENT_ROOT']) )) . '?_CAPTCHA&amp;t=' . urlencode(microtime());
        $image_src = '/' . ltrim(preg_replace('/\\\\/', '/', $image_src), '/');
    } else {
        $_SERVER['WEB_ROOT'] = str_replace($_SERVER['SCRIPT_NAME'], '', $_SERVER['SCRIPT_FILENAME']);
        $image_src = substr(__FILE__, strlen( realpath($_SERVER['WEB_ROOT']) )) . '?_CAPTCHA&amp;t=' . urlencode(microtime());
        $image_src = '/' . ltrim(preg_replace('/\\\\/', '/', $image_src), '/');
    }
    $_SESSION['_CAPTCHA']['config'] = serialize($captcha_config);
    return array(
        'code' => $captcha_config['code'],
        'image_src' => $image_src
    );
}
if( !function_exists('hex2rgb') ) {
    function hex2rgb($hex_str, $return_string = false, $separator = ',') {
        $hex_str = preg_replace("/[^0-9A-Fa-f]/", '', $hex_str); 
        $rgb_array = array();
        if( strlen($hex_str) == 6 ) {
            $color_val = hexdec($hex_str);
            $rgb_array['r'] = 0xFF & ($color_val >> 0x10);
            $rgb_array['g'] = 0xFF & ($color_val >> 0x8);
            $rgb_array['b'] = 0xFF & $color_val;
        } elseif( strlen($hex_str) == 3 ) {
            $rgb_array['r'] = hexdec(str_repeat(substr($hex_str, 0, 1), 2));
            $rgb_array['g'] = hexdec(str_repeat(substr($hex_str, 1, 1), 2));
            $rgb_array['b'] = hexdec(str_repeat(substr($hex_str, 2, 1), 2));
        } else {
            return false;
        }
        return $return_string ? implode($separator, $rgb_array) : $rgb_array;
    }
}

if( isset($_GET['_CAPTCHA']) ) {
    session_start();
    $captcha_config = unserialize($_SESSION['_CAPTCHA']['config']);
    if( !$captcha_config ) exit();
    if( isset($_GET['_RENDER']) ) {
        $_SESSION['_CAPTCHA'] = simple_php_captcha();
    } else {
        unset($_SESSION['_CAPTCHA']);
    }
    
    $background = $captcha_config['backgrounds'][mt_rand(0, count($captcha_config['backgrounds']) -1)];
    list($bg_width, $bg_height, $bg_type, $bg_attr) = getimagesize($background);
    $captcha = imagecreatefrompng($background);
    $color = hex2rgb($captcha_config['color']);
    $color = imagecolorallocate($captcha, $color['r'], $color['g'], $color['b']);
    
    $angle = mt_rand( $captcha_config['angle_min'], $captcha_config['angle_max'] ) * (mt_rand(0, 1) == 1 ? -1 : 1);
    
    $font = $captcha_config['fonts'][mt_rand(0, count($captcha_config['fonts']) - 1)];
    
    if( !file_exists($font) ) throw new Exception('Font file not found: ' . $font);
    
    $font_size = mt_rand($captcha_config['min_font_size'], $captcha_config['max_font_size']);
    $text_box_size = imagettfbbox($font_size, $angle, $font, $captcha_config['code']);
    
    $box_width = abs($text_box_size[6] - $text_box_size[2]);
    $box_height = abs($text_box_size[5] - $text_box_size[1]);
    $text_pos_x_min = 0;
    $text_pos_x_max = ($bg_width) - ($box_width);
    $text_pos_x = mt_rand($text_pos_x_min, $text_pos_x_max);
    $text_pos_y_min = $box_height;
    $text_pos_y_max = ($bg_height) - ($box_height / 2);
    if ($text_pos_y_min > $text_pos_y_max) {
        $temp_text_pos_y = $text_pos_y_min;
        $text_pos_y_min = $text_pos_y_max;
        $text_pos_y_max = $temp_text_pos_y;
    }
    $text_pos_y = mt_rand($text_pos_y_min, $text_pos_y_max);
    
    if( $captcha_config['shadow'] ){
        $shadow_color = hex2rgb($captcha_config['shadow_color']);
        $shadow_color = imagecolorallocate($captcha, $shadow_color['r'], $shadow_color['g'], $shadow_color['b']);
        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']);
    }
    
    imagettftext($captcha, $font_size, $angle, $text_pos_x, $text_pos_y, $color, $font, $captcha_config['code']);
    
    header("Content-type: image/png");
    imagepng($captcha);
}




Now question is how to use above function to display captcha code and validation on server.
The following code will prepare a CAPTCHA image and keep the code in a session variable for later use:

<?php
session_start();
include("simple-php-captcha.php");
$_SESSION['captcha'] = simple_php_captcha();
?>

After the call to simple_php_captcha() above, $_SESSION['captcha'] will be something like this:

Array
(
    [code] => YkXw3
    [image_src] => /simple-php-captcha/simple-php-captcha.php?_CAPTCHA&t=0.80665100+1559223924
)

To display the CAPTCHA image, create an HTML img using $_SESSION['captcha']['image_src'] as the src attribute:

To verify the CAPTCHA value on the next page load (or in an AJAX request), test against $_SESSION['captcha']['code']. You can use strtolower() or strtoupper() to perform a case-insensitive match.

Configuration
Configuration is easy and all values are optional. To specify one or more options, do this:

<?php
 
$_SESSION['captcha'] = simple_php_captcha( array(
    'min_length' => 5,
    'max_length' => 5,
    'backgrounds' => array(image.png', ...),
    'fonts' => array('font.ttf', ...),
    'characters' => 'ABCDEFGHJKLMNPRSTUVWXYZabcdefghjkmnprstuvwxyz23456789',
    'min_font_size' => 28,
    'max_font_size' => 28,
    'color' => '#666',
    'angle_min' => 0,
    'angle_max' => 10,
    'shadow' => true,
    'shadow_color' => '#fff',
    'shadow_offset_x' => -1,
    'shadow_offset_y' => 1
));
 
>

Notes:

  • Important! Make sure you call session_start() before
    calling the simple_php_captcha() function
  • Requires PHP GD2 library
  • Backgound images must be in PNG format
  • Fonts must be either TTF or OTF
  • Backgrounds and fonts must be specified using their full paths (tip: use
    $_SERVER['DOCUMENT_ROOT'] . '/' . [path-to-file])
  • Angles should not exceed approximately 15 degrees, as the text will sometimes
    appear outside of the viewable area
  • Creates a function called simple_php_captcha() in the global namespace
  • Uses the $_SESSION['simple-php-captcha'] session variable

See live demo and download source code.

DEMO | DOWNLOAD

This awesome script developed by yasirmturk, Visit their official github repository for more information and follow for future updates.

Don’t forget to Subscribe My Public Notebook for more useful free scripts, tutorials and articles.

Posted in PHP