Simple PHP Captcha Using CodexWorldCaptcha


Full form of CAPTCHA is Telling Humans and Computers Apart Automatically. CAPTCHA is a program which helps to protect your website from bots and determine the user is human or not. So, you need to add CAPTCHA for protecting contact form, comment form and any other forms from spam.

There are so many third party solutions for implementing the CAPTCHA functionality in your site. One of the popular third party CAPTCHA solutions is Google reCAPTCHA and we have published new Google reCAPTCHA with PHP tutorial earlier. But many times you need to add a simple PHP captcha in form. This tutorial helps you to implement CAPTCHA functionality using PHP in your website.

simple-php-captcha-by-codexworld

We have created a CodexWorldCaptcha PHP class which provides you highly customization option for PHP captcha. Using CodexWorldCaptcha script you can easily add captcha to the form.

CodexWorldCaptcha.php

Main CodexWorldCaptcha class contains 2 functions createCaptcha() and hexToRgb(). hexToRgb() function is used by createCaptcha() function, so you should need to call only createCaptcha() function.

<?php

/** 
 *
 * Author: CodexWorld  
 * Author URI: http://www.codexworld.com  
 * Author Email: contact@codexworld.com
 * Class Name: CodexWorldCaptcha 
 * Description: CodexWorldCaptcha is a free PHP Captcha script used for generating captcha image.  
 *
 **/

class CodexWorldCaptcha
{
    
//Configuration Options
    
var $word '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    var 
$length 5;
    var 
$img_width 160;
    var 
$img_height 50;
    var 
$font_path '';
    var 
$font_size 25;
    var 
$expiration 7200;
    var 
$bg_color '#ffffff';
    var 
$border_color '#996666';
    var 
$text_color '#cc9999';
    var 
$grid_color '#ffb6b6';
    var 
$shadow_color '#fff0f0';
    
    public function 
__construct($config = array()){
        
ob_start();
        session_start();
        if (
count($config) > 0){
            foreach (
$config as $key => $val){
                if (isset(
$this->$key)){
                    
$method 'set_'.$key;
                    if (
method_exists($this$method)){
                        
$this->$method($val);
                    }else{
                        
$this->$key $val;
                    }
                }
            }
        }
        

        if ( ! 
extension_loaded('gd')){
            return 
FALSE;
        }
    }
    
    public function 
createCaptcha(){
        
$str '';
        for (
$i 0$i $this->length$i++){
            
$str .= substr($this->wordmt_rand(0strlen($this->word) -1), 1);
        }
        
$word $str;

        
/* Determine angle and position */
        
$length strlen($word);
        
$angle  = ($length >= 6) ? rand(-($length-6), ($length-6)) : 0;
        
$x_axis rand(6, (360/$length)-16);
        
$y_axis = ($angle >= ) ? rand($this->img_height$this->img_width) : rand(6$this->img_height);

        
/* Create image */
        
if (function_exists('imagecreatetruecolor')){
            
$im imagecreatetruecolor($this->img_width$this->img_height);
        }else{
            
$im imagecreate($this->img_width$this->img_height);
        }

        
/* Assign colors */
        
$bgColorRgb  $this->hexToRgb($this->bg_color);
        
$borderColorRgb $this->hexToRgb($this->border_color);
        
$textColorRgb $this->hexToRgb($this->text_color);
        
$gridColorRgb $this->hexToRgb($this->grid_color);
        
$shadowColorRgb $this->hexToRgb($this->shadow_color);
        
$bg_color       imagecolorallocate ($im$bgColorRgb[0], $bgColorRgb[1], $bgColorRgb[2]);
        
$border_color   imagecolorallocate ($im$borderColorRgb[0], $borderColorRgb[1], $borderColorRgb[2]);
        
$text_color     imagecolorallocate ($im$textColorRgb[0], $textColorRgb[1], $textColorRgb[2]);
        
$grid_color     imagecolorallocate($im$gridColorRgb[0], $gridColorRgb[1], $gridColorRgb[2]);
        
$shadow_color   imagecolorallocate($im$shadowColorRgb[0], $shadowColorRgb[1], $shadowColorRgb[2]);

        
/* Create the rectangle */
        
ImageFilledRectangle($im00$this->img_width$this->img_height$bg_color);

        
/* Create the spiral pattern */
        
$theta  1;
        
$thetac 7;
        
$radius 16;
        
$circles20;
        
$points  32;

        for (
$i 0$i < ($circles $points) - 1$i++){
            
$theta $theta $thetac;
            
$rad  $radius * ($i $points );
            
$x  = ($rad cos($theta)) + $x_axis;
            
$y  = ($rad sin($theta)) + $y_axis;
            
$theta $theta $thetac;
            
$rad1 $radius * (($i 1) / $points);
            
$x1  = ($rad1 cos($theta)) + $x_axis;
            
$y1  = ($rad1 sin($theta )) + $y_axis;
            
imageline($im$x$y$x1$y1$grid_color);
            
$theta $theta $thetac;
        }

        
/* Write the text in image */
        
$use_font = ($this->font_path != '' AND file_exists($this->font_path) AND function_exists('imagettftext')) ? TRUE FALSE;

        
$x rand(0$this->img_width/($length/1.5));
        
$y $this->font_size+2;

        for (
$i 0$i strlen($word); $i++)
        {
            if (
$use_font == FALSE){
                
$y rand($this->img_height/2);
                
imagestring($im$this->font_size$x$ysubstr($word$i1), $text_color);
                
$x += ($this->font_size);
            }else{
                
$y rand($this->img_height/2$this->img_height-3);
                
imagettftext($im$this->font_size$angle$x$y$text_color$this->font_pathsubstr($word$i1));
                
$x += $this->font_size;
            }
        }

        
/* Create the image border */
        
imagerectangle($im00$this->img_width-1$this->img_height-1$border_color);

        
/* Showing the image */
        
imagejpeg($im,NULL,90);
        
header('Content-Type: image/jpeg');//image type header
        
imagedestroy($im);//destroying image
        
        /* Store captcha code into session */
        
if(empty(session_id()))
        unset(
$_SESSION['captchaCode']);
        
$_SESSION['captchaCode'] = $word;
    }
    
    public function 
hexToRgb($hex){
        
$hex str_replace("#"""$hex);
        if(
strlen($hex) == 3) {
           
$r hexdec(substr($hex,0,1).substr($hex,0,1));
           
$g hexdec(substr($hex,1,1).substr($hex,1,1));
           
$b hexdec(substr($hex,2,1).substr($hex,2,1));
        } else {
           
$r hexdec(substr($hex,0,2));
           
$g hexdec(substr($hex,2,2));
           
$b hexdec(substr($hex,4,2));
        }
        
$rgb = array($r$g$b);
        return 
$rgb;
    }
}

?>

index.php

This file is used to display the form with PHP CAPTCHA and validate the captcha code.

<?php
session_start
();
if(isset(
$_POST['submit']) && !empty($_POST['submit'])){
    if(!empty(
$_POST['captcha_code'])){
        
        
//get captcha code from session
        
$captchaCode $_SESSION['captchaCode'];
        
        
//get captcha code from input field
        
$enteredcaptchaCode $_POST['captcha_code'];
        
        
//verify the captcha code
        
if($enteredcaptchaCode === $captchaCode){
            
$succMsg 'Entered captcha code has matched.';
        }else{
            
$errMsg 'Captcha code not matched, please try again.';
        }
        
    }else{
        
$errMsg 'Please enter the captcha code.';
    }
}
?>

<?php if(!empty($errMsg)) echo '<p style="color:#EA4335;">'.$errMsg.'</p>';?>
<?php 
if(!empty($succMsg)) echo '<p style="color:#34A853;">'.$succMsg.'</p>';?>
<img src="captcha.php" id="capImage"/> <br/>Can't read the image? click here to <a href="javascript:void(0);" onclick="javascript:$('#capImage').attr('src','captcha.php');">refresh</a>. <form method="post"> Enter the code: <input name="captcha_code" type="text" value=""> <input type="submit" name="submit" value="SUBMIT"> </form>

Also you should need to include the jQuery library for refreshing the captcha image.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

captcha.php

This file is used to generate the captcha image using CodexWorldCaptcha class.

<?php
include 'CodexWorldCaptcha.php';
$captchaConfig = array(
     
'img_width' => '200',
     
'img_height' => '50',
     
'font_size' => '30',
     
'font_path' => 'fonts/monofont.ttf',
 );
$captcha = new CodexWorldCaptcha($captchaConfig);
$captcha->createCaptcha();
?>

Leave a reply

Connect With CodexWorld