Simple string to image based free PHP Captcha Code

In web Captcha is the Technique using which we can protect spam users. Today hackers are very cleaver. Let’s talk about a login page. Here someone can easily enter spam records using a script. Captcha gives confirmation that the user is a real-human. The story behind Captcha is “We generate a random string and store that in server. In the next moment showing the same string to the user as an image. To validate comparing server session value with user input against the image”. In below demo app I am creating a PHP Captcha.

Here I defined 4 functions CAPTCHA, randomString, hexadecimalToRGB and alignImageToCenter. The function CAPTCHA is responsible to Create Captcha image. It accepts 4 params $textColor, $backgroundColor, $imgWidth, $imgHeight. $textColor is the color for text. $backgroundColor is the captcha background. $imgWidth & $imgHeight is decides area for capatch. randomString function generating random strings which I am converting later into Captcha image. hexadecimalToRGB is the color converter function. While generating image alignImageToCenter is responsible for aling random string to center.

The base function to generate Captcha is “CAPTCHA”. In this function initially I am with some configurable variables. Then generating a random string and providing style. Finally using PHP imagettftext() function generating the Captcha image.

PHP-Captcha.php

<?php
/*Executing the Function Captcha*/
CAPTCHA('#162453', '#fff', 120, 40);

/*Function to Generate Captcha*/
function CAPTCHA($textColor, $backgroundColor, $imgWidth, $imgHeight)
{
/* Configuration Settings */
$font = './font/mono.ttf';
$fontSize = $imgHeight * 0.75;
$textColor = hexadecimalToRGB($textColor);

/*Generating and Storing random string to $rnd variable*/
$rnd = randomString();

$im = imagecreatetruecolor($imgWidth, $imgHeight);	
$textColor = imagecolorallocate($im, $textColor['r'], $textColor['g'], $textColor['b']);			

$bgColor = hexadecimalToRGB($backgroundColor);
$backgroundColor = imagecolorallocate($im, $bgColor['r'],$bgColor['g'],$bgColor['b']);				

imagefill($im, 0, 0, $backgroundColor);	
list($x, $y) = alignImageToCenter($im, $rnd, $font, $fontSize);	
imagettftext($im, $fontSize, 0, $x, $y, $textColor, $font, $rnd);		

/*Displaying image*/
imagejpeg($im, NULL, 90);

/*Declaring Image Type*/
header('Content-Type: image/jpeg');
imagedestroy($im);/* Destroying image instance */

/*Storing the random string to a Session variable*/
if(isset($_SESSION)){
$_SESSION['captcha_code'] = $rnd;/* set random text in session for captcha validation*/
}
}

/*This for is responsible to generate Random string for Captcha*/
function randomString($length=6){
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}

/*Using this function I am extracting RBG value form Hexadecimal Color*/
function hexadecimalToRGB($colour)
{
$hex = str_replace("#", "", $colour); 

if(strlen($hex) == 3) { 
$red = hexdec(substr($hex,0,1).substr($hex,0,1)); 
$green = hexdec(substr($hex,1,1).substr($hex,1,1)); 
$blue = hexdec(substr($hex,2,1).substr($hex,2,1)); 
} else { 
$red = hexdec(substr($hex,0,2)); 
$green = hexdec(substr($hex,2,2)); 
$blue = hexdec(substr($hex,4,2)); 
}
return array( 'r' => $red, 'g' => $green, 'b' => $blue );
}		

/*Function to position Image to the Center*/
function alignImageToCenter($image, $text, $font, $size, $angle = 8) 
{
$xi = imagesx($image);
$yi = imagesy($image);
$box = imagettfbbox($size, $angle, $font, $text);
$xr = abs(max($box[2], $box[4]));
$yr = abs(max($box[5], $box[7]));
$x = intval(($xi - $xr) / 2);
$y = intval(($yi + $yr) / 2);
return array($x, $y);	
}
?>

To run the above code additionally you required to Create a font folder in root directory. Download a ttf image file. Put that in the font folder. Without ttf font file this PHP Captcha program will not run.