Sunday, January 27, 2013

How to Create CAPTCHA Protection using PHP

there are following stpes
1. html code
<img src="/captcha.php/?rand=0.608989860869691" id="captcha_image"/>
<a href="javascript:void(0);" onClick="refreshcaptcha();" >Refresh</a>
<input type="text" name="norobot" id="norobot" value="Enter Image Code" />

2. js
function refreshcaptcha(){
    var capimage = document.getElementById('captcha_image').src;  
    var full_img=capimage.split('rand=');  
    document.getElementById('captcha_image').setAttribute('src', full_img[0]+'rand='+Math.random());
}

3.captcha.php
$randomnr = rand(1000, 9999);
$session["randomnr"] = md5($randomnr));
   
   
    $im = imagecreatetruecolor(100, 38);

    $white = imagecolorallocate($im, 255, 255, 255);
    $grey = imagecolorallocate($im, 150, 150, 150);
    $black = imagecolorallocate($im, 0, 0, 0);

    imagefilledrectangle($im, 0, 0, 200, 35, $black);

    //path to font - this is just an example you can use any font you like:
   
    $font =  '/font/karate/Karate.ttf';

    imagettftext($im, 20, 4, 22, 30, $grey, $font, $randomnr);

    imagettftext($im, 20, 4, 15, 32, $white, $font, $randomnr);
    
    //die(111);
    //prevent caching on client side:
    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");

    header ("Content-type: image/gif");
    imagegif($im);
    imagedestroy($im);
    exit;

4. On post action file
if (md5($data['norobot']) == $session["randomnr"])    {
                // here you  place code to be executed if the captcha test passes
 }    else { 
                // here you  place code to be executed if the captcha test fails
                    echo "Please enter correct code.";
                    return;
}


No comments:

Post a Comment