Tuesday, 1 July 2014

Captcha Using PHP



CAPTCHA  which stands for “Completely Automated Public Turing test to tell Computers and Humans Apart” is a type o f challenge-response test to ensure that the response is only generated by humans and not by a computer.

In simple words, CAPTCHA is the word verification test that you will come across the end of a sign-up form while signing up for Gmail or Yahoo account. The following image shows the typical samples of CAPTCHA.

You can make captcha using PHP. Here I am making number captcha which is achieved by an image. This image text is dynamically create by php and stored in session. A user can verify whether valid captcha has been entered or not.



Save this code in named captch.php

<?php 
session_start(); 
$text = rand(10000,99999); 
$_SESSION["vercode"] = $text; 
$height = 25; 
$width = 65; 
  

$image_p = imagecreate($width, $height); 
$black = imagecolorallocate($image_p, 0, 0, 0); 
$white = imagecolorallocate($image_p, 255, 255, 255); 
$font_size = 14; 
  
imagestring($image_p, $font_size, 5, 5, $text, $white); 
imagejpeg($image_p, null, 80); 
?>

Index page code

<?php
session_start();  
if($_POST["code"]== $_SESSION["vercode"])
$msg="Ok You 're human";
else
$msg="Invalid code";
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>

<body>
<form action=<?php echo "$_SERVER[PHP_SELF]" ?> method="post"> 
Enter Code <img src="captcha.php">
<input type="text" name="code" /> 
<input type="submit" name="ccode" value="Submit" /> 
<span style="font-size:large;color:#FF0000">
<?php 
echo $msg;
?>
</span>
</form>
</body>
</html>