How to create captcha code in PHP


Have you ever got spam email from your website’s contact form or facing any type of security vulnerability on any form on your website ? If answer is yes,then this is the time to prevent your form from web attackers or automated scripts. So before we go ahead let’s discuss a little bit about captcha.

What is CAPTCHA?

CAPTCHA is the short form of Completely Automated Public Turing Test to tell Computers and Humans Apart. It is used to prevents automatated programme and bot.Because suppose you have a form and there is no any captcha code then an attacker can post their data to your form using either PHP CURL function or google chrome’s postman Addons or any automated programme. CAPTCHA generates an image file with text,digits or image randomly. An automated programme may read the image but it cannot guess what has been written in the image and a human can easily read the image. So this way captcha protects your web form. Today we will see how to use captcha security image in PHP.

Below is the captcha class which defines all the methods and properties for generate a captcha security image.


class Captcha{
	public $width=100;//newly generated Image  Width
	public $height=40;//newly generated Image Height
	public $background_color='24A6EA';//Default Background Color
	public $text_color='F3F3F9'; //Default text Color
	public $distort_image=true;
	public $distort_type='line';
	public $total_distort=20; //How many line/ellipse generate
	public $distort_color='951E43'; //distorted color code
	 * Which type of image the captcha will generate.Available type is (text/digit/random)
	public $show_type='random'; //text/digit/random
	public $show_char;//Store character/digit
	public $text_only='ABCDEFGHIJKLMNOPQRSTUVWXYZ'; //Only character
	public $digit_only='0123456789'; //Only Digit
	public $show_num=5;//How many character/number will show (default is 5)
	public $font="arial.ttf"; //Font Type
	public $font_size=20; //Font Size
	/*This constructor function will generate the Captcha Image*/
	public function __construct(){
			//For Background color
			$background = imagecolorallocate($im,$bg_color_arr[0],$bg_color_arr[1],$bg_color_arr[2]);						
			imagefill($im, 0, 0, $background);
			//For Text color
			$text_color = imagecolorallocate($im,$text_color_arr[0],$text_color_arr[1],$text_color_arr[2]);		
			//For Distort the Image
				$_SESSION['CaptchaCode'] = $ShowText;/* set random text in session for captcha validation*/
			header('content-type: image/jpeg');/* defining the image type to be shown in browser widow */
			imagettftext($im, $this->font_size, 0, $cordinate_size["x"], $cordinate_size["y"], $text_color, $this->font, $ShowText);
			imagejpeg($im,NULL,90);/* Showing image */			
			imagedestroy($im);/* Destroying image instance */			
		}catch (Exception $e) {
			echo $e->getMessage();
	/*For distort the image background*/
	private function IsImageDistort($im){
				$distort_img_color = imagecolorallocate($im,$color_arr[0],$color_arr[1],$color_arr[2]);
					case 'line':
						for( $i=0; $i<$this->total_distort; $i++ ) {
							imageline($im, mt_rand($i,$this->width), mt_rand($i,$this->height),mt_rand($i,$this->width), mt_rand($i,$this->height), $distort_img_color);						
					case 'ellipse':
						for( $i=0; $i<$this->total_distort; $i++ ) {
							imagefilledellipse($im, mt_rand(0,$this->width), mt_rand(0,$this->height), 3, 3, $distort_img_color);						
	/*This function will return hexadecimal Code
	  If hash(#) is include then remove the hash
	private function getColorCode($color){
		return $ColorArr;
	 * which type of code this function will generate (text/digit/random)
	private function showImageType(){		
			case 'text': //For Text Only
			case 'digit': //For Digit Only
			case 'random': //For Random Only					
		return $this->show_char;
	/*Text for center alignment*/
	private function getImageAlignment($im){				
		$box = imagettfbbox($this->font_size, 8, $this->font, $this->showImageType());
		$x=$box[0] + (imagesx($im) / 2) - ($box[4] / 2);
		$y = $box[1] + (imagesy($im) / 2) - ($box[5] / 2) - 5;		
		return array("x"=>$x,"y"=>$y);		

Above class has 4 private methods and 1 constructor.IsImageDistort() private method is used to generate line/ellipse on the image background. getColorCode() private method returns the color code in hexadecimal value with 3 array. Next private method i.e. showImageType() returns which type of code you want to generate and finally getImageAlignment() private method returns the text alignment in x and y array.

Below are property of captcha and you can call the property as per your requirements.

Property Name Use
$width Set the width of newly create image. Default width is 100
$height Set the height of newly create image. Default height is 40
$background_color Set the background color of captcha image. Default background color is 24A6EA
$text_color Set the text color of the image. Default text color is F3F3F9
$distort_image If value is true then captcha image will add a line or ellipse on the image background. Default value is true
$total_distort When $distort_image value is set to true then this property set how many line or ellipse genarate on the image background. Default value is 20
$distort_color If $distort_image is set to true then this property set the background color of line or ellipse.Default color is 951E43
$show_type Whether the script generate text/digit/random captcha image. Default is random
$text_only Generates only alphabetic character
$digit_only Generates only digits
$show_num How many characters/digits wilol show in the captcha image. Default is 5
$font Defines the True Text Type font
$font_size Defines the font size of the captcha. Default is 20

How to Create captcha code with refresh button ?

If you want to generate different captcha code without reloading your webpage, then you can do it with 2 lines of javascript code. below are the code.

<script type="text/javascript">
function getNewCaptcha(){
	document.getElementById('LoadNewCaptcha').src="captcha.php?random=" + Math.random();

In the above code the function getNewCaptcha() get the id of <img tag name with “LoadNewCaptcha” and set the image src to “captcha.php?random=” + Math.random(). Most users get confused why we have used random=” + Math.random() because it generates random code for example “captcha.php?random=0.4385508431007814”. Everytime you click on the refresh button the script behaves it as a new URL. if you use only document.getElementById(‘LoadNewCaptcha’).src=”captcha.php then it will generate the same image again and again.

How to use the captcha code in PHP Script

Finally we have prepared all our required resources. Now this is the time to implement.

Note: Whenever you call the captcha code make sure have start your session with session_start(). otherwise the script doesn’t work.

Now create an index.php file where we will call the captcha image.

	if(isset($_SESSION["CaptchaCode"]) && $_SESSION["CaptchaCode"]!=$_POST["security_code"]){
		$error='Invalid captcha code';
		//Your code	
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>How to Create Captcha Code</title>
<form action="" method="post">
if(isset($error) && $error !=''){
	echo $error;	
<input type="text" name="security_code" />&nbsp;<img id="LoadNewCaptcha" src="captcha.php" />
<input type="button" onClick="getNewCaptcha()" value="Generate New Image" />
<input type="submit" value="Submit" />

Thank you for viewing. Keep in touch for more tutorials.

Leave a comment


Enter your email address to subscribe to this blog and receive notifications of new posts by email.