serving the solutions day and night

Pages

Tuesday, May 4, 2010

CAPTCHA Image Code - PHP, AJAX

CAPTCHA - Completely Automated Public Turing test to tell Computers and Humans Apart
A CAPTCHA is used to ensure that the response is not generated by a computer, means response from human. It is used to distinguish between human and bots.


HTML Form Code
<script>
function resetCaptcha()
{
document.getElementById('imgCaptcha').src = 'captchaimage.php?' + Math.random();
}
</script>
<div>
<img src="captchaimage.php" id="imgCaptcha">
<img src="refresh.jpeg" border=0 id="imgRefresh" onclick="setTimeout('resetCaptcha()', 300); return false;">
</div>

PHP CODE - captchaimage.php
<?php
  $captcha = PHPCaptchaImage();
  function PHPCaptchaImage()
  {
    /* Define number characters contains the captcha image, declare global */
    $iTotalChars= 6;
    /* Size image height and width, declare globl */
    $iHeight='40';
    $iWidth='170';
    /* font style */
    $sFontStyle = '\fonts\arial.ttf';
    /* Possible characters in the image */
    $sImageChars = '01%2^34&56*789Ab!cD@eF#gH$iJkLmNoPqRsTUvwxyZ';
    $sImageCode = '';

    for ($i = 0; $i<$iTotalChars; $i++)
      $sImageCode .= substr($sImageChars, mt_rand(0, strlen($sImageChars)-1), 1);
    $sImageCode_array = str_split($sImageCode, 1);

    /* @imagecreate() function is used to create a new palette based image using the GD Library.
       Font size is 80% of the image height */
    $fFontSize = $iHeight * 0.80;
    $oImageName = @imagecreate($iWidth, $iHeight) or die('Cannot initialize new GD image stream');

    /* imagecolorallocate(resource $image, int $red, int $green, int $blue) function is used to 
       set the  color for an image */
    imagecolorallocate($oImageName, 20, 40, 100);  // Background Color
    $iTextColor = imagecolorallocate($oImageName, 255, 255, 55);   
    $iNoiseColor = imagecolorallocate($oImageName, 55, 255, 55);

    /* imagefilledellipse(resource $image, int $cx, int $cy, int $width, int $height, int $color)  
       function is used draws an ellipse, generate random dots in background */
    for( $i=0; $i<($iWidth*$iHeight)/3; $i++ )
      imagefilledellipse($oImageName, mt_rand(0,$iWidth), mt_rand(0,$iHeight), 1, 1, $iNoiseColor);

    /* imageline(resource $image, int $x1, int $y1, int $x2, int $y2, int $color)function used to 
       generate line, generate random lines in background */
    for( $i=0; $i<($iWidth*$iHeight)/150; $i++ )
      imageline($oImageName, mt_rand(0,$iWidth), mt_rand(0,$iHeight), mt_rand(0,$iWidth), mt_rand(0,$iHeight), $iNoiseColor);

    /* array imagettfbbox(float $size, float $angle, string $fontfile, string $text)function is used to 
       create textbox and add text. It returns an array with 8 elements.
       key contents
      0 lower left corner, X position
      1 lower left corner, Y position
      2 lower right corner, X position
     3 lower right corner, Y position
     4 upper right corner, X position
     5 upper right corner, Y position
     6 upper left corner, X position
     7 upper left corner, Y position */
    $aTextBoundBox = imagettfbbox($fFontSize, 0, $sFontStyle, $sImageCode) or die('Error in imagettfbbox function');
    $dXPosition = ($iWidth - $aTextBoundBox[4])/2;
    $dYPosition = ($iHeight - $aTextBoundBox[5])/2;

  /*array imagettftext(resource $image, float $size, float $angle, int $x, int $y, int $color, string
   $fontfile, string $text)function is used to write text to the image using fonts. */
    //imagettftext($oImageName, $fFontSize, 0, $dXPosition, $dYPosition, $iTextColor, $sFontStyle , $sImageCode) or die('Error in imagettftext function');
      for($i=0;$i<=$iTotalChars;$i++)
      {
         $image_text_direction = mt_rand('1','2');
          if($image_text_direction == 1)
          {
              imagettftext($oImageName,  20, -mt_rand('15','30'), $dXPosition, 30, $iTextColor, $sFontStyle,
              $sImageCode_array[$i]);
          }
          else
          {
               imagettftext($oImageName, 20, mt_rand('15','30'), $dXPosition, 30, $iTextColor, $sFontStyle,
               $sImageCode_array[$i]);
           }
           $dXPosition = $dXPosition+($iWidth/8);
       }

    /* output captcha image to browser */
    header('Content-Type: image/jpeg');

    /* imagejpeg function is used to create jpeg image */
    imagejpeg($oImageName);

    /* imagedestroy function is used destory an image object */
    imagedestroy($oImageName);

    $_SESSION['dns_security_code'] = $sImageCode;
  }
?>
Use AJAX code to Reload CAPTCHA image in the form. Once form submitted,use JavaScript to validate CAPTCHA image text value is not empty. Then use PHP code to validate user input CAPTCHA image text value and SESSION value, if it both are same, then process further oterwise throw verification is not valid in the error message.

2 comments:

Jim Kraus said...

A very useful link! Thanks Mohideen

andrew siddle said...

Nice job... i have been looking for good Captcha Code i think i found it.....