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.

Generate_Captcha.php
<?php
session_start();
$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);
imagefill($target_layer,0,0,$captcha_background);
$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");
imagejpeg($target_layer);
?>

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


<div  style="width:400px;margin:100px auto;">
Captcha :
<br>
<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>" ;
}
 
}
?></div><br>
<input type="submit" name="submit" value="Submit">

</div>

</form>
</body>
</html>

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.
Compare_Captcha.php
<?php
session_start();
if(count($_POST)>0) {
if($_POST["captcha_code"]==$_SESSION["captcha_code"]){
$message = "You have entered correct captcha";
}
else{
$message = "Please enter Correct Captcha Code";
}
}
?>

Download Link :

https://github.com/skptricks/php-Tutorials/blob/master/Captcha%20tutorials.rar

No comments:

Post a Comment