Wednesday, 12 March 2014

PHP Captcha Code Example Code Snippets

Captcha
CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) is a type of challenging-response test used in computer field to determine whether user is Human OR robot program. Captcha is used in website to confirm that your website is accessing by a human being not machine. We can add captcha in multiple form/pages of website.

It reduce the risk of hacking/damage of website. It also help to secure the web server.


Follow Simple Steps to add captcha in your website.

1. Copy the following code and put in createCaptch.php
session_start();
//Let's generate a totally random string using md5
$md5_hash_no = md5(rand(0, 999));
//We don't need a 32 character long string so we trim it down to 5
$security_code = substr($md5_hash_no, 15, 5);
$_SESSION['captcha'] = $security_code;

//Set the image width and height
$width = 148;
$height = 37;

//Create the image resource
$image = ImageCreate($width, $height);

//We are making three colors, white, black and gray
$white = ImageColorAllocate($image, 255, 255, 255);
$black = ImageColorAllocate($image, 0, 0, 0);
$grey = ImageColorAllocate($image, 204, 204, 204);

//Make the background black
ImageFill($image, 0, 0, $grey);

//Add randomly generated string in white to the image
ImageString($image, 8, 50, 10, $security_code, $black);

//$font = 'font1.ttf';
//imagettftext($image, 18, 0, 15, 28, $black, $font, $security_code);
//Throw in some lines to make it a little bit harder for any bots to break
ImageRectangle($image, 0, 0, $width - 1, $height - 1, $grey);

// prevent client side  caching
header("Expires: Wed, 1 Jan 1997 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");


//Tell the browser what kind of file is come in
header("Content-Type: image/jpeg");

//Output the newly created image in jpeg format
ImageJpeg($image);

2. In the Form add following

<input name="ccode" type="text" /> <img src="createCaptch.php" title="Captcha Code" />

3
. Validate the captcha
session_start();
if($_POST['ccode']==$_SESSION['captcha']){
    //valid 
}ELSE{
    //Invalid
}