Categories
PHP

mathCaptcha – Really simple captcha

Sometimes captchas are way too complicated. Just in mind I have the one from rapidshare and the cats…Impossible!

What I’m showing up today is a really simple captcha. With a bit of security of course.

Script Name: mathCaptcha
Version: 0.1
License: GPL v3
Screenshot:
mathCaptcha

Live Demo
Download

Installation:

Just download the .zip file , uncompress in your htdoc and try 😉

Support: forum.neo22s.com

Usage:

We have 2 functions in the file mathCaptcha.php

The first one is used to obfuscate the result of the captcha since is not an image, this makes a bit more difficult for the bots to read the result.

function encode_str ($input)//converts the input into Ascii HTML
{
    for ($i = 0; $i < strlen($input); $i++) {
         $output .= "&#".ord($input[$i]).';';
    }
    return $output;
}

Then we have the function that generates the math and stores it in a session (remember to have at the beginning of the page).

Right now I only add as an operator +, but you can use the one you want just changing the code, also the numbers for the operation can be changed in the mt_rand

session_start();
function mathCaptcha(){//generates a captcha for the form
	$first_number=mt_rand(1, 94);//first operation number
	$second_number=mt_rand(1, 5);//second operation number
	$_SESSION["mathCaptcha"]=($first_number+$second_number);//operation result
	$operation=" ".encode_str($first_number ." + ". $second_number)."?";//operation codifieds
	echo "How much is:".$operation;
}

Then to display the captcha and add the input to write in, it is really simple (using 1 form):

< ?php mathCaptcha();?>

This would display the captcha and one input to write the numbers in.

As you can see I used one JavaScript function just to control that they write numbers in the input, is something really stupid but I think is user friendly:

function isNumberKey(evt){
	var charCode = (evt.which) ? evt.which : event.keyCode;
	if((charCode==46||charCode==8||charCode==45||charCode==47) ||(charCode >= 48 && charCode < = 57) ){
		return true;
	}
	else {
		return false;
	}
}

Once the form is submited we need to check if they are humans, to do this we can use something like:

if ($_POST){//if there's post action
	if($_POST["math"] == $_SESSION["mathCaptcha"])	{//correct it seems human
		echo "Great Einstein! your answer is the good one.

"; } else echo "Wrong! I think you missed some school lessons, try another time.

"; }

And that’s all folks.

Notes:
It is important to have the proper charset. BTW uses PHP if was not clear xD