Skip to main content

Build Reusable Captcha Script with PHP

A CAPTCHA(Completely Automated Public Turing test to tell Computers and Humans Apart) is a type of challenge code that used in web applications to determine that the action is done by human being.

Captcha code is a combination of some readable text with some distorted shapes to be read only by human being to confirm that the user is not a bot.

There are many third party resources available to easily add Captcha to your web application. But if you’re looking for creating your own custom Captcha code to use in your project then you’re here right place. In this tutorial, you will learn how to create your own reusable Captcha script using PHP to user in your future projects.

We will explain this tutorial step by step with live example to implement Captcha with PHP. We will create a HTML form with input text, Captcha image and submit button to display Captcha and enter into input text to validate form submission with valid Captcha code.

Also, read:

So let’s create live example of Captcha script using PHP. The major files are:

  • index.php
  • captcha.php
  • captcha_code.js

Step1: Include Bootstrap, jQuery Files

As we will create live example of Captcha using PHP, jQuery and Bootstrap design, so first we will include Bootstrap and jQuery files.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

Step2: Desgin Form with Captcha Code

In index.php file, we will design HTML form with input text, Captcha image and submit button. We will call captcha.php in img src with random number to load Captcha code when form loaded. We will also create refresh link to refresh Captcha code when click refresh link.

<div class="container">	
	<div class="row">			
		<div class="col-md-6">
			<div class="col-md-12">
				<form name="form" class="form" action="" method="post">								
					<div class="form-group">
						<label for="captcha" class="text-info">
						<?php if($statusMessage) { ?>
							<span class="text-danger"><strong><?php echo $statusMessage; ?></strong></span>
						<?php } ?>	
						</label><br>
						<input type="text" name="captchaText" id="captchaText" class="form-control" placeholder="Enter Captcha code">
					</div>
					<div class="form-group">								
						<img src="captcha.php?rand=<?php echo rand(); ?>" id='captchaCode'>
						<br>
						<p><br>Wants new Captcha code? <a href="javascript:void(0)" id="refreshCaptchaCode">refresh</a></p>
					</div>										
					<div class="form-group">	
						<input type="submit" name="submit" class="btn btn-info btn-md" value="Submit">								
					</div>							
				</form>
			</div>
		</div>
	</div>
</div>

Step3: Create Captcha Code

In captcha.php file, we will implement functionality to create PHP Session based Captcha with PHP. We will create Captcha image with height 50 and width 130 pixels with total 5 characters on Captach image. The final Captcha code will be stored into $_SESSION['captchaCode'] session variable to checked when form submitted with Captcha code.

<?php
session_start();
$captchaCode = '';
$captchaImageHeight = 50;
$captchaImageWidth = 130;
$totalCharactersOnImage = 6; 
$possibleCaptchaLetters = 'abcdefghhkmnopqrstuvwxyz98765432';
$captchaFont = 'monofont.ttf'; 
$randomCaptchaDots = 50;
$randomCaptchaLines = 25;
$captchaTextColor = "a94442";
$captchaNoiseColor = "a94442"; 
$characterCount = 0;
while ($characterCount < $totalCharactersOnImage) { 
	$captchaCode .= substr($possibleCaptchaLetters, mt_rand(0, strlen($possibleCaptchaLetters)-1), 1);
	$characterCount++;
} 
$captchaFont_size = $captchaImageHeight * 0.65;
$captchaImage = @imagecreate(
	$captchaImageWidth,
	$captchaImageHeight
); 
$backgroundColor = imagecolorallocate(
 $captchaImage,
 255,
 255,
 255
); 
$arrayTextColor = hextorgb($captchaTextColor);
$captchaTextColor = imagecolorallocate(
 $captchaImage,
 $arrayTextColor['red'],
 $arrayTextColor['green'],
 $arrayTextColor['blue']
); 
$arrayNoiseColor = hextorgb($captchaNoiseColor);
$imageNoiseColor = imagecolorallocate(
 $captchaImage,
 $arrayNoiseColor['red'],
 $arrayNoiseColor['green'],
 $arrayNoiseColor['blue']
); 
for( $captchaDotsCount=0; $captchaDotsCount<$randomCaptchaDots; $captchaDotsCount++ ) {
imagefilledellipse(
	 $captchaImage,
	 mt_rand(0,$captchaImageWidth),
	 mt_rand(0,$captchaImageHeight),
	 2,
	 3,
	 $imageNoiseColor
 );
}
for( $captchaLinesCount=0; $captchaLinesCount<$randomCaptchaLines; $captchaLinesCount++ ) {
	imageline(
		$captchaImage,
		mt_rand(0,$captchaImageWidth),
		mt_rand(0,$captchaImageHeight),
		mt_rand(0,$captchaImageWidth),
		mt_rand(0,$captchaImageHeight),
		$imageNoiseColor
	);
} 
$text_box = imagettfbbox(
	$captchaFont_size,
	0,
	$captchaFont,
	$captchaCode
); 
$x = ($captchaImageWidth - $text_box[4])/2;
$y = ($captchaImageHeight - $text_box[5])/2;
imagettftext(
	$captchaImage,
	$captchaFont_size,
	0,
	$x,
	$y,
	$captchaTextColor,
	$captchaFont,
	$captchaCode
); 
header('Content-Type: image/jpeg'); 
imagejpeg($captchaImage); 
imagedestroy($captchaImage);
$_SESSION['captchaCode'] = $captchaCode; 
function hextorgb ($hexstring){
	$integar = hexdec($hexstring);
	return array(
		"red" => 0xFF & ($integar >> 0x10),
		"green" => 0xFF & ($integar >> 0x8),
		"blue" => 0xFF & $integar
	);
}
?>

Step4: Display Captcha Code

We will call captcha.php file and pass rand number to load Captcha code image.

<div class="form-group">								
	<img src="captcha.php?rand=<?php echo rand(); ?>" id='captchaCode'>
	<br>
	<p><br>Wants new Captcha code? <a href="javascript:void(0)" id="refreshCaptchaCode">refresh</a></p>
</div>

Step5: Refresh Captcha code

In captcha_code.js file, we will implement Captcha code refresh functionality. We will handle Captcha code refresh code functionality when refresh link clicked and reset Captcha image src with new random number to refresh code.

$(document).ready(function(){
	$("#refreshCaptchaCode").click(function(){
		var img = $('#captchaCode').attr('src');	
		img = img.substring(0,img.lastIndexOf("?"));
		img = img+"?rand="+Math.random()*1000;
		$('#captchaCode').attr('src', img);
	});
});

Step6: Validate Form with Captcha code

We will validate Captcha code when form submitted by checking original code from session $_SESSION['captchaCode'] and user entered form input Captcha code $_POST['captchaText'] and displayed message accordingly.

<?php
session_start();
$statusMessage = '';
if ( isset($_POST['captchaText']) && ($_POST['captchaText']!="")){
	if(strcasecmp($_SESSION['captchaCode'], $_POST['captchaText']) != 0){
		$statusMessage = "It seems you have entered invalid captcha code! Please try again.";
	}else{
		$statusMessage = "Your captcha code have been matched successfully."; 
	}
} else {
	$statusMessage = "Enter captcha code."; 
}
?>

You may also like:

You can view the live demo from the Demo link and can download the script from the Download link below.
Demo Download