Wednesday, 4 January 2012

PHP Human Verification ( captcha ) Script.

Step 1 Generate a String of ramdom cheractors
function random_string()
{
$string="";
$c="";//Random char buffer
$i=0;
for($i=0;$i<=4;$i++)
{
$s = rand(65,90);//generates a random cheractor and store in $s
$string=$string.sprintf("%c",$s);//Can-cads random character to $string.
} 
return $string;
} 



Step 2 Store the generated String in a secession variable.
session_start();
$_SESSION["key"]=random_string();


Step 3 Display generated string as an image in html forum.
function for image generation.
function generate_textimage($string)
{
        $myImage = imagecreate(200, 50);
        $myGray = imagecolorallocate($myImage, 250, 255, 255);
        $black = imagecolorallocate($myImage, 0, 0, 0);
        putenv('GDFONTPATH=' . realpath('.'));

        $font='pirulen.ttf';
        imagettftext($myImage, 25, 0, 20, 30, $black, $font, $string);
imagefilter($myImage, IMG_FILTER_GAUSSIAN_BLUR);
        ob_start();
        imagepng($myImage);
        printf('<img src="data:image/png;base64,%s"/>', 
                base64_encode(ob_get_clean()));
        imagedestroy($myImage);
}

Over all usage

<pre class="brush:[php];"><html>
    <head>

        <title></title>
    </head>
    <body>
<?php
require_once("huveri.php");
session_start();
//Generate Random String
$string = random_string();

$_SESSION["key"]=$string;

?>

        <?php generate_textimage($string); ?>

        <form action="vali.php" method="post">
        <input type="text" name="key" />
        <input type="submit" value="Submit" />
        </form>
    </body>
</html>




Step 4 Do some verification in form action.


<?php
session_start();

if($_SESSION["key"]==$_POST["key"])
{
    echo "Wellcome Human";
   
    }else {
        echo "Your not Human";
        }

session_destroy();

?>