Last updated on January 25th, 2022 at 04:42 pm

Simple php captcha script

This script will show how to create captcha image using php. We have captcha.php, class.simplecaptcha.php,white.png and 3 font files. We will provide clear working scripts and a demo on integrating captcha using php.

The file captcha.php contains all the settings on how to change the font , the image file etc.,

<?php
session_start();
require_once('class.simplecaptcha.php');
/*
*****CONFIGURATION STARTS*****
*/
//Background Image
$config['BackgroundImage'] = "white.png";

//Background Color- HEX
$config['BackgroundColor'] = "FFFC00";

//image height - same as background image
$config['Height']=30;

//image width - same as background image
$config['Width']=100;

//text font size
$config['Font_Size']=23;

//text font style(Complete Path )
$config['Font']="/var/captcha/BOOKOS.TTF";

//text angle to the left
$config['TextMinimumAngle']=15;

//text angle to the right
$config['TextMaximumAngle']=45;

//Text Color - HEX
$config['TextColor']='000000';

//Number of Captcha Code Character
$config['TextLength']=6;

//Background Image Transparency
$config['Transparency']=50;

/*
*******CONFIGURATION ENDS******
*/

//Create a new instance of the captcha
$captcha = new SimpleCaptcha($config);

//Save the code as a session dependent string
$_SESSION['string'] = $captcha->Code;
?>
 

Now class.simplecaptcha.php

<?php
class SimpleCaptcha {

function SimpleCaptcha( $params = null )
{
$this->BackgroundImage = $params['BackgroundImage']; //background image
$this->BackgroundColor = $params['BackgroundColor'];
$this->Height = $params['Height']; //image height
$this->Width = $params['Width']; //image width
$this->FontSize = $params['Font_Size']; //text font size
$this->Font = $params['Font']; //text font style
$this->TextMinimumAngle = $params['TextMinimumAngle'];
$this->TextMaximumAngle = $params['TextMaximumAngle'];
$this->TextColor = $params['TextColor'];
$this->TextLength = $params['TextLength'];
$this->Transparency = $params['Transparency'];

$this->generateCode();
//initially, png is used
header("Content-type: image/png");
$this->generateImage($this->Code);

}
//Background Images
function getBackgroundImage()
{
   return $this->BackgroundImage;
}

function setBackgroundImage( $background_image = null )
{
   $this->BackgroundImage = $background_image;
}

//Backgroung Color
function getBackgroundColor()
{
    return $this->BackgroundColor;
}

function setBackgroundColor( $background_color )
{
   $this->BackgroundColor = $background_color;

}

//Image Height
function getHeight()
{
   return $this->Height;
}

function setHeight( $height = null )
{
   $this->Height = $height;
}
//Image Width
function getWidth()
{
   return $this->Width;
}

function setWidth( $width = null )
{
   $this->Width = $width;
}
//Font size
function getFontSize()
{
   return $this->FontSize;
}

function setFontSize( $size = null )
{
   $this->FontSize = $size;
}

//Font
function getFont()
{
   return $this->Font;
}

function setFont( $font = null )
{
   $this->Font = $font;
}

//Text Minimum Angle
function getTextMinimumAngle()
{
   return $this->TextMinimumAngle;
}

function setTextMinimumAngle( $minimum_angle = null )
{
   $this->TextMinimumAngle = $minimum_angle;
}

//Text Maximum Angle
function getTextMaximumAngle()
{
   return $this->TextMaximumAngle;
}

function setTextMaximumAngle( $maximum_angle = null )
{
   $this->TextMaximumAngle = $maximum_angle;
}

//Text Color
function getTextColor()
{
   return $this->TextColor;
}

function setTextColor( $text_color )
{
   $this->TextColor = $text_color;
}

//Text Length
function getTextLength()
{
   return $this->TextLength;
}

function setTextLength( $text_length = null )
{
   $this->TextLength = $text_length;
}

//Transparency
function getTransparency()
{
   return $this->Transparency;
}

function setTransparency( $transparency = null )
{
   $this->Transparency = $transparency;
}

//get Captcha Code
function getCode()
{
return $this->Code;
}

//Generate Captcha
function generateCode()
{
        $length = $this->getTextLength();
        $this->Code = "";
        while(strlen($this->Code)<$length){
            mt_srand((double)microtime()*1000000);
            $random=mt_rand(48,122);
            $random=md5($random);
            $this->Code .= substr($random, 17, 1);
        }

        return $this->Code;
}


function generateImage($text = null)
{
$im = imagecreatefrompng( $this->getBackgroundImage() );
$tColor = $this->getTextColor();
$txcolor = $this->colorDecode($tColor);
$bcolor = $this->getBackgroundColor();
$bgcolor = $this->colorDecode($bcolor);
$width = $this->getWidth();
$height = $this->getHeight();
$transprency = $this->getTransparency();
$this->im = imagecreate($width,$height);
$imgColor = imagecolorallocate($this->im, $bgcolor['red'], $bgcolor['green'], $bgcolor['blue']);
imagecopymerge($this->im,$im,0,0,0,0,$width,$height,$transprency);
$textcolor = imagecolorallocate($this->im, $txcolor['red'], $txcolor['green'], $txcolor['blue']);
$font = $this->getFont();
$fontsize=$this->getFontSize();
$minAngle = $this->getTextMinimumAngle();
$maxAngle = $this->getTextMaximumAngle();
$length = $this->getTextLength();

for($i=0;$i<$length;$i++){
imagettftext(
             $this->im,
             $fontsize,
             rand(-$minAngle,$maxAngle),
             $i*15+10,
             $this->FontSize*1.2,
             $textcolor,
             $font,
             substr($text, $i, 1));
}

imagepng($this->im);
imagedestroy($this->im);
}

function colorDecode( $hex ){

   if(!isset($hex)) return FALSE;

   $decoded['red'] = hexdec(substr($hex, 0 ,2));
   $decoded['green'] = hexdec(substr($hex, 2 ,2));
   $decoded['blue'] = hexdec(substr($hex, 4 ,2));

   return $decoded;

}
}
?>

DOWNLOAD THE FONT 1
DOWNLOAD THE FONT 2
DOWNLOAD THE FONT 3

AND PNG FILE

How to configure the above files in to a login/contact form, Add the below code on your html FORM. Modify it according to your need.

<?php
  ob_start();
  session_start();
?>
<html>
  <head>
    <title>Simple CAPTCHA App</title>
  </head>
  <body>
<?php if (!$_POST['code'])
  {
  ?>
      <form id="demo" action="<?php echo $_SERVER['PHP_SELF']; ?>?goto=login" method="POST">

            Message:
            <br/>
            <textarea name="message" cols="25" rows="5" id="message" ></textarea>
            <br/>
            Validation Code:
            <br/>
            <img src="captcha.php" alt="CAPTCHA">
            <br>
            <input type="text" name="code" size="30">
            <br>
            <input type="submit" value="Go">
      </form>
        <?php
     }else{

        //Check if userinput and CAPTCHA Code are equal
        if ($_SESSION['string'] == $_POST['code'])
        {
          echo '<script>alert("Correct Code.");history.go(-1);</script>';
echo "SUCCESSFUL";
        }
        else
        {
          echo '<script>alert("Incorrect Code.");history.go(-1);</script>';
           }
      }
    ?>

DEMO
Note: Make sure to provide complete path for the font file for example

//text font style
$config['Font']="<absolute_path_of_this_file>/BOOKOS.TTF";

2 thoughts on “How to create php captcha script”
  1. I believe other website proprietors should take this website as an model, very clean and fantastic user pleasant pattern.

Leave a Reply

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