Saturday, August 19, 2017

PHP Captcha

In this tutorial, I will discuss over Captcha. Basically CAPTCHA is a program that protects websites against bots by generating and grading tests that humans can pass but current computer programs cannot.
Now a days Captcha code is very popular in web based application and it will prevent from roberts to enter the irrelevant data in web page. This script compare the CAPTCHA image with user entered text.

PHP code generate CAPTCHA
In this part, we have used rand() function to generate random number and afterwards we convert that random number to image file by script. One more thing that I want to cover here is that, we used PHP session concept to store that random number, later on we can use it for comparison purpose.

$random_alpha = md5(rand());
$captcha_code = substr($random_alpha, 0, 6);
$_SESSION["captcha_code"] = $captcha_code;
$target_layer = imagecreatetruecolor(70,30);
$captcha_background = imagecolorallocate($target_layer, 255, 160, 119);
$captcha_text_color = imagecolorallocate($target_layer, 0, 0, 0);
imagestring($target_layer, 5, 5, 5, $captcha_code, $captcha_text_color);
header("Content-type: image/jpeg");

Display Captcha HTML Form
This part of code will display HTML Form with CAPTCHA.
Captcha form.php
<title>Contact Us Form</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
<?php include("Compare_Captcha.php"); ?>
<form name="frmContact" method="post" action="">

<div  style="width:400px;margin:100px auto;">
Captcha :
<img src="Generate_Captcha.php" /><br><br>
Type the captcha here : 
<br/><input name="captcha_code" type="text"><br>
<div style ="color:red;" class="message"><?php 
if( isset($_POST['captcha_code'] ) ){ 

if($message == "You have entered correct captcha"){
 echo "<div style ='color:green;' class='message'>$message</div><br>" ;
if($message == "Please enter Correct Captcha Code"){
 echo "<div style ='color:red;' class='message'>$message</div><br>" ;
<input type="submit" name="submit" value="Submit">



Compare Captcha Code
When we submit the form, then our script will compare the entered text with $_SESSION variable. If the match found it will show success message otherwise it will show error message.
if(count($_POST)>0) {
$message = "You have entered correct captcha";
$message = "Please enter Correct Captcha Code";

Download Link :

No comments:

Post a Comment