Simple Captcha with PHP


Simple Captcha with PHP
 
Captcha is an acronym for "Completely Automated Public Turing test to tell Computers and Humans Apart" (Wikipedia), and made to distinguish between machines (bots) and human.


Implementation:
Captcha often used to 'secure' form from bot attacks, e.g. on contact forms, registration forms, etc.. This time, we will try to make a simple captcha by using simple mathematics test (sum).

file: captcha.php


<?php
session_start();
$img = "img.jpg"; //image used as background
//color
$red = "255"; // range from 0 - 255
$green = "255";
$blue = "255";

//--- drawing ----
$random1 = mt_rand(3,10); // random value1
$random2 = mt_rand(6,20); // random value 2
$strview = $random1." + ".$random2;
$result = $random1 + $random2;
$makeimg =imagecreatefromjpeg($img);
$text = imagecolorallocate($makeimg, $red, $green, $blue);
imagestring($makeimg, 5, 20, 10, $strview, $text);
$_SESSION['capcay'] = $result;
header("Content-type: image/jpeg");
imagejpeg($makeimg);
?>

This script will add random values. Random value is obtained from the function mt_rand(). The result of the sum of these random values will be saved into a session which will serve to check the input of the form.
 
file: form.php 

<?php
session_start();
if(isset($_POST['check'])){
   if($_POST['ccheck'] == $_SESSION['capcay']){
      echo "True";
   } else {
      echo "Wrong";
   }
}
?>
<form action="" method="post">
  <img src="captcha.php"/> <br />
<input name="ccheck" type="text"/>
<input name="check" type="submit" value="Check..!!"/>
</form>

form.php file is a file that is used as input. When the button 'submit' button, then the script will check whether the input is entered is the same as the previous session that generated the file captcha.php


4 comments:

andrew siddle said...

thanks.....
you provide me great information about how to create Captcha Code

TopHTML said...

You're welcome Andrew, thanks for visiting. I'll visit your website too..

Sean said...

This looks nice and simple, but I'm afraid you are missing out the crucial part - how to implement it into an existing form that needs a captcha?

MyAdmin said...

Sean, you're right. This script is only an example how to make simple captcha. It needs an improvement. Thanks.

Post a Comment