How To Use Ajax For Image Verification Aka CAPTCHA

Welcome. Please Login, Register, Or Activate! 
type your username and password to login
Date: November 22, 2009, 02:57 AM
430659 members and 297808 Topics
Latest Member: DanielM
Nairaland [Nigerian Forum] Home Help Search Who is currently online? Login Register
Nairaland Forum  |  Technology  |  Webmasters (Moderators: OmniPotens, yawa-ti-de)  |  How To Use Ajax For Image Verification Aka CAPTCHA
Pages: (1) Go Down Send this topic Notify of replies
Author Topic: How To Use Ajax For Image Verification Aka CAPTCHA  (Read 1117 views)
*dhtml
How To Use Ajax For Image Verification Aka CAPTCHA
« on: January 04, 2009, 03:54 PM »

So now we are going to have a short workshop on how to protect your site from bots by doing what we call a CAPTCHA

(Completely Automated Public Turing test to tell Computers and Humans Apart):  A category of technologies used to ensure that a human is making an online transaction rather than a computer. Developed at Carnegie Mellon University, random words or letters are displayed in a camouflaged and distorted fashion so that they can be deciphered by people, but not by software. Users are asked to type in the text they see to verify they are human.

CAPTCHAs were created in response to bots (software agents) that automatically fill in Web forms as if they were individual users. Bots are used to overload opinion polls, steal passwords (see dictionary attack) and, most popular, to register thousands of free e-mail accounts to be used for sending spam. CAPTCHAs were designed to circumvent non-humans from performing such transactions.

The feature of the one we are going to use is going to be with ajax such that you can use it without reloading your page.

Demo link http://mwebng.net/demos/captcha/
Download link : http://mwebng.net/?net=dl
*dhtml
Re: How To Use Ajax For Image Verification Aka CAPTCHA
« #1 on: January 04, 2009, 04:34 PM »

The files there are listed as follows:

index.php - the form we want to secure
captcha.php - the image generator
verdana.ttf - the font file used on the server for the image
post.php - your form submission script
refresh.gif - the captcha refresh button



* Untitled-1.gif (4.55 KB, 421x162 )
*dhtml
Re: How To Use Ajax For Image Verification Aka CAPTCHA
« #2 on: January 04, 2009, 04:36 PM »

index.php
Code:
<html>
<head>
<title>Ajax Captcha</title>
<script>
function reset_captcha() {
document.getElementsByName("captcha").value="";
with(document.getElementById('imgCaptcha')) {
src = "";
src = 'captcha.php?' + Math.random();
}
}

function validate(form) {
if(form.fullname.value=="") {alert("Please enter your name to continue, ");form.fullname.focus();return false;}
if(form.captcha.value=="") {alert("Please enter verification code.");form.captcha.focus();return false;}
return true;
}
</script>
</head>
<body>

<form action="post.php" onsubmit="return validate(this)">
<table>
<tr><td>
Full Name: </td>
<td>
<input style="width:200" type="text" name="fullname" value=""><br>
</td></tr>


<tr><td>
Type the code shown:
</td>
<td><input style="width:200" type="text" autocomplete="off" name="captcha">
</td>
</tr>


<tr><td style="padding:10;" align="right">
<img src="refresh.gif" border=0 id="captcha_image" onclick="setTimeout('reset_captcha()', 300); return false;"  style="cursor:hand">
</td>
<td>
<img src="captcha.php" id="imgCaptcha">
</td>
</tr>

<tr><td>&nbsp;</td>
<td><input type="submit" value="Send">
</td>
</tr>

</table>
</form>

</body> </html>
*dhtml
Re: How To Use Ajax For Image Verification Aka CAPTCHA
« #3 on: January 04, 2009, 04:38 PM »

The script portion
Code:
function reset_captcha() {
document.getElementsByName("captcha").value="";
with(document.getElementById('imgCaptcha')) {
src = "";
src = 'captcha.php?' + Math.random();
}
}

function validate(form) {
if(form.fullname.value=="") {alert("Please enter your name to continue, ");form.fullname.focus();return false;}
if(form.captcha.value=="") {alert("Please enter verification code.");form.captcha.focus();return false;}
return true;
}
This contains 2 functions - one for refreshing the image and another function for validating the form. You do not need to manipulate the reset_captcha function.
*dhtml
Re: How To Use Ajax For Image Verification Aka CAPTCHA
« #4 on: January 04, 2009, 04:39 PM »

Code:
<tr><td>
Type the code shown:
</td>
<td><input style="width:200" type="text" autocomplete="off" name="captcha">
</td>
</tr>


<tr><td style="padding:10;" align="right">
<img src="refresh.gif" border=0 id="captcha_image" onclick="setTimeout('reset_captcha()', 300); return false;"  style="cursor:hand">
</td>
<td>
<img src="captcha.php" id="imgCaptcha">
</td>
</tr>

<input style="width:200" type="text" autocomplete="off" name="captcha"> holds the typed value for the captcha

while

<img src="captcha.php" id="imgCaptcha"> will load the captcha image from captch.php - which actually renders an image

*dhtml
Re: How To Use Ajax For Image Verification Aka CAPTCHA
« #5 on: January 04, 2009, 04:41 PM »

Ehm, This code is a bit long  - but i will just say what it does - it creates an image using randomly generated text
it uses the text to create an image and keeps the text into session data as $_SESSION["security_code"]
You may need to readup image generation functions in php - but not needed to use this tool.

captcha.php
Code:
<?
//Start the session so we can store what the security code actually is
session_start();

//Send a generated image to the browser
create_image();
exit();

function str_rand($string_length, $string_type='numeric') {
        $string_array = array('numeric','alpha','alnum','alnum_cap','alnum_low','alpha_cap','alpha_low');
        if(array_search($string_type, $string_array) !== FALSE) {
            if($string_length < 40) {
                switch($string_type) {
                    case 'numeric':
                        $string_seed = range('1','9');
                    break;
                    case 'alpha':
                        $string_seed = array_merge(range('A','Z'), range('a','z'));
                    break;
                    case 'alpha_cap':
                        $string_seed = range('A','Z');
                    break;
                    case 'alpha_low':
                        $string_seed = range('a','z');
                    break;
                    case 'alnum':
                        $string_seed = array_merge(range('1','9'), array_merge(range('A','Z'), range('a','z')));
                    break;
                    case 'alnum_cap':
                        $string_seed = array_merge(range('1','9'), range('A','Z'));
                    break;
                    case 'alnum_low':
                        $string_seed = array_merge(range('1','9'), range('a','z'));
                    break;
                }
                $string_random = '';
                for($i=0;$i<$string_length;$i++) {
                    $string_key = array_rand($string_seed, 1);
                    $string_random .= $string_seed[$string_key];
                }
                return $string_random;
            }
            else {
                return 'Invalid string length';
            }
        }
        else {
            return 'Invalid string type';
        }
    }


function create_image()
{
$image_width = 197;
    $image_height = 40;
    $image_base = imagecreatetruecolor($image_width,$image_height);
    $image_background = imagecolorallocate($image_base, 250, 250, 250);
    imagefill($image_base, 0, 0, $image_background);
    if(isset($_GET['s'])) {
        $image_text = $_GET['s'];
    }
    else {
        $image_text = str_rand(6, 'alnum');
    }


    //Set the session to store the security code
    $_SESSION["security_code"] = $image_text;


    $image_text_array = str_split($image_text, 1);
    $image_text_color = imagecolorallocate($image_base,0,0,0);
    $image_font = 'verdana.ttf';
    $image_letter = ($image_width/8);
    header('Content-type: image/png');
    for($i=0;$i<=16;$i++) {
        $image_line_color = imagecolorallocatealpha($image_base,mt_rand('0','200'),mt_rand('0','200'),mt_rand('0','200'),mt_rand('20','115'));
        imagesetthickness($image_base,mt_rand('1','3'));
        imageline($image_base,mt_rand('0',$image_width),mt_rand('0',$image_height),mt_rand('0',$image_width),mt_rand('0',$image_height),$image_line_color);
    }
    $image_dots_spacing = 10;
    $image_dots_y = $image_height/$image_dots_spacing;
    for($i=0;$i<=$image_dots_y;$i++) {
        $image_line_color = imagecolorallocatealpha($image_base,mt_rand('0','200'),mt_rand('0','200'),mt_rand('0','200'),mt_rand('20','115'));
        imagesetthickness($image_base,2);
    }
    for($i=0;$i<=6;$i++) {
        $image_text_direction = mt_rand('1','2');
        if($image_text_direction == 1) {
            imagettftext($image_base, 20,-mt_rand('5','15'),$image_letter,30,$image_text_color,$image_font,$image_text_array[$i]);
        }
        else {
            imagettftext($image_base, 20,mt_rand('5','15'),$image_letter,30,$image_text_color,$image_font,$image_text_array[$i]);
        }
        $image_letter = $image_letter+($image_width/8);
    }
    imagepng($image_base);
    imagedestroy($image_base);
}
?>
*dhtml
Re: How To Use Ajax For Image Verification Aka CAPTCHA
« #6 on: January 04, 2009, 04:43 PM »

post.php
Code:
<?php
session_start
();

if (
$_REQUEST["captcha"] != $_SESSION["security_code"]) {
print<<<end
<font color="red">Sorry Your Verification Code is wrong.</font>
end;
} else {
print<<<end
<font color="blue">You are welcome to Mediweb Solutions Nigeria Enterprises, </font>
end;
}
include 
"index.php";
?>

This looks simple iight? it just compares the stored session autogenerated captcha with wat was just submitted
and is able to tell if it is right or wrong.



*************************************** The End *******************************************


Questions can now fall in - if any that is.

Abidemi_A
Re: How To Use Ajax For Image Verification Aka CAPTCHA
« #7 on: January 05, 2009, 12:53 PM »

Good Job, thank you.

But one thing

If you click the submit button without typing the correct values on the image, the content of the datafield is not retained after generating new image value. Assuming  I am a user, and I have completed a form with over 20 textboxes, does it mean I will loose all I have entered because I made mistake while typing the image value?
*dhtml
Re: How To Use Ajax For Image Verification Aka CAPTCHA
« #8 on: January 05, 2009, 02:54 PM »

@abidemi, good of you to show yourself here - now i am expecting you to give us that are not good with asp a similar solution with aspx.
Anyway, as for your question - i am tryin to keep codes simple so that those that wish to learn - can learn easily.
I will eventually have to talk about form validation in one of my threads - not yet. Meanwhile the codes i have been posting so far are extracts from my past works - i just remove the tech parts and break it down into simple codes for ppl to follow - the idea is not to be posting codes indiscriminately!
 Website Review: FelaDurotoye.com  Affiliate Check Collection Service  How Do I Start Accepting Credit Card Payments On My Site?  Page 2
Pages: (1) Go Up Send Topic to Friend by E-mail Reply 


Sections: Autos/Cars (2) Jobs/Vacancies (2) (3) Career Talk Education General(2) Politics Romance Computers Phones Travel
Sports Fashion Health Religion Celebrities TV/Movies (2) Music/Radio (2) Books Webmasters Programming

Links: Page1 Page2 Page3 Page4 Page5 Page6 Page7 Page8 Page9 Page10

Nairaland is owned by Oluwaseun Osewa. See also: Nairalist Classified Ads
Nairaland Forum | Powered by SMF 1.0.12.
© 2001-2005, Lewis Media. All Rights Reserved.