Home > AJAX, PHP > Simple AJAX Captcha

Simple AJAX Captcha


Advertisement



September 25th, 2008 Admin Leave a comment Go to comments

Nowaday in Web 2.0 realm, AJAX become primary need for web developer to create a dynamic web applications. Not only web developer, but also spammer getting more dynamic and clever :( Usually they fill in comment box or input user to put their junk content like backlinks. To avoid this, it’s commonly to used CAPTCHA since they effective enough to blocked spammer.

But now it’s Web 2.0! AJAX in everywhere. So let’s create a simple AJAX Captcha to accomodate this. First searched for Google and found it, there’s enough resource to make a improvisation with this stuff (How to Create CAPTCHA Protection using PHP and AJAX and FunkyAJAX). I tried at home but no one of them have a complete feature but still simple :) So i combine all resource and build this one, simple but have a full feature that i wanted!

You can check DEMO to get transparent on this. I’ve included AJAX Captcha to avoid a high resource consumed (server).

Universal AJAX Link Checker


First, build a simple form with textarea, single input user, img tag, and of course submit button (you can pass this).

<html>
<head>
<title>Simple AJAX CAPTCHA by SmileyLover.Com</title>
<script language="JavaScript" type="text/javascript" src="ajax_captcha.js"></script>
</head>
<body>
<form action="javascript:get(document.getElementById('myform'));" name="myform" id="myform">
	<textarea id="mytextarea" name="mytextarea" cols="25" rows="5"></textarea><br />
 
	<img id="imgCaptcha" src="create_image.php" onclick="setTimeout('refreshimg()', 300); return false;" alt="Click on me to change image"/>&nbsp;&nbsp;
	<input id="txtCaptcha" type="text" name="txtCaptcha" value="" maxlength="10" size="10" autocomplete="off"/>
 
	<br /><small><i><b>* Click on the CAPTCHA to refreshing image!</b></i></small>
	<br />
 
	<input type="button" name="button" value="Submit" 
	   onclick="javascript:get(this.parentNode);">
	<input type="submit" name="button" value="Normal Submit Button" >
 
</form>
 
<br><br>
Server-Response:<br>
<span name="myspan" id="myspan"></span>
<br /><br />
Powered by <a href="http://blog.smileylover.com/">SmileyLover.Com</a>
</body>
</html>

This form also work if you just press ENTER instead click submit button. So now the javascript code. Basically it’s using XMLHttpRequest like ordinary AJAX Post/Get but we also send a session from image from Captcha. I’ve added this line into var getstr.

“&txtCaptcha=” + encodeURI( document.getElementById(“txtCaptcha”).value) ;

txtCaptcha is ID being used for Captcha input user . So we need to Captcha change dynamically when AJAX response is return. We need this code. Add to javascript in condition if (http_request.status == 200).

//Get a reference to CAPTCHA image
img = document.getElementById(‘imgCaptcha’);
//Change the image
img.src = ‘create_image.php?’ + Math.random(); // Search for new image
document.getElementById(‘txtCaptcha’).value=”; //Reset input Captcha after succes return

There’s already information about code above. Session is create by create_image.php itself. For more sophiscated we need to change image when user click on it (if user can’t read Captcha) of course with AJAX. Add this little bit code.

// IMAGE REFRESHING
function refreshimg()
{
//Get a reference to CAPTCHA image
img = document.getElementById(‘imgCaptcha’);
//Change the image
img.src = ‘create_image.php?’ + Math.random();
}

So now is full Javascript code.

?View Code JAVASCRIPT
   var http_request = false;
   function makeRequest(url, parameters) {
      http_request = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
         	// set type accordingly to anticipated content type
            //http_request.overrideMimeType('text/xml');
            http_request.overrideMimeType('text/html');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!http_request) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
      http_request.onreadystatechange = alertContents;
      http_request.open('GET', url + parameters, true);
      http_request.send(null);
   }
 
   function alertContents() {
      if (http_request.readyState == 4) {
         if (http_request.status == 200) {
            //alert(http_request.responseText);
            result = http_request.responseText;
            document.getElementById('myspan').innerHTML = result; 
			//Get a reference to CAPTCHA image
			img = document.getElementById('imgCaptcha'); 
			//Change the image
			img.src = 'create_image.php?' + Math.random(); // Search for new image
			document.getElementById('txtCaptcha').value=''; //Reset input Captcha  after succes return 			
         } else {
            alert('There was a problem with the request.');
         }
      }
   }
 
   function get(obj) {
      var getstr = "?" +
			"&mytextarea=" + encodeURI( document.getElementById("mytextarea").value) +
			"&txtCaptcha=" + encodeURI( document.getElementById("txtCaptcha").value) ;
      makeRequest('get.php', getstr);
   }
 
// IMAGE REFRESHING
function refreshimg()
{
	//Get a reference to CAPTCHA image
	img = document.getElementById('imgCaptcha'); 
	//Change the image
	img.src = 'create_image.php?' + Math.random();
}

Now look for create_image.php, it’s common php generate Captcha with session_start() function and $_SESSION["name_session"]. You can download all source code in the end of this posting.

<?
//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 create_image() 
{ 
    //Let's generate a totally random string using md5 
    $md5_hash = 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, 15, 5); 
 
    //Set the session to store the security code
    $_SESSION["security_code"] = $security_code;
 
    //Set the image width and height 
    $im = imagecreate(80, 25);
 
    //white background and blue text
    $bg = imagecolorallocate($im, 255, 255, 255);
	$textcolor = imagecolorallocate($im, 128, 0, 0);
 
    //Add randomly generated string in white to the image
    ImageString($im, 5, 20, 8, $security_code, $textcolor); 
 
    //Tell the browser what kind of file is come in 
    header("Content-Type: image/jpeg"); 
 
    //Output the newly created image in jpeg format 
    ImageJpeg($im); 
 
    //Free up resources
    ImageDestroy($im); 
} 
?>

Now the last script. For example we want get.php for handling all input from AJAX. So let’s look this simple script.

<?php
//Continue the session
session_start();
 
if ( ($_GET["txtCaptcha"] == $_SESSION["security_code"]) && (!empty($_GET["txtCaptcha"]) && !empty($_SESSION["security_code"])) ) {
 
	//If CAPTCHA success
	echo "Success <br />";
	print_r($_GET);
 
} else { //If CAPTCHA invalid!
	echo 'You entered an invalid CAPTCHA! <br />Please fill in again ...';
}
?>

Simple right? Since we used GET method for AJAX request fo we define input user by $_GET. As i promised, you can download all code here.

Download AJAX Captcha Code

Simple AJAX Captcha Demo

Simple AJAX Captcha Demo

Have a nice day :)

Related posts:

  1. AJAX POST GET Form With Multiple Checkbox, Radio, Select Option
  2. WordPress Exchange Links Plugin – AJAX Version
  3. Free CB Plugin Simple Invitation (Invite Friends)
  4. Auto Add Friends Using (Javascript) Friendster Hacks
  5. Simple Callback Script For Tracking Your Script
Categories: AJAX, PHP Tags:
  1. October 20th, 2008 at 09:20 | #1

    tx for the code, i’ll try it :)

  2. April 10th, 2009 at 12:12 | #2

    Thank you bro. Tak coba nanti :D

    • Admin
      April 10th, 2009 at 16:38 | #3

      U r the master :)

  3. Nasir
    July 6th, 2009 at 10:31 | #4

    The Captcha not working i am wonder why it is not working than why you publish it

    • Admin
      July 6th, 2009 at 10:33 | #5

      it’s for most people :)

      just read README file carefully..

      anyway you can post ur URL in here

      regards

      • December 30th, 2009 at 12:48 | #6

        Hi!
        Thanks for it, but there is no readme file on the archive, do you mean something else?

        • Admin
          December 30th, 2009 at 13:19 | #7

          yes, no readme … this is simple coding … u can try to integrate with ur main php, but pls view the coding bout validate

          please remember to place session_start(); in begining your php file :)

          regards

          • December 30th, 2009 at 13:51 | #8

            Thx for your reply.
            But, first, I’m a beginner in php (it does not mean that I don’t know anything ^^)
            second, The thing is that the index.htm file in your archive don’t work, it’s not my integration…

          • Admin
            December 30th, 2009 at 14:41 | #9

            hi, can u more specific what u need? please :)
            regards

  4. December 30th, 2009 at 15:06 | #10

    @admin:
    Hi :D
    At the begining, I was searching for a captcha that don’t refresh the page afer sending the code; I found this but it’s pointing to a website that’s gone (here).
    I found yours but it don’t work: here is a screen of what I mean : click here to view the screenshot.

    I hope you understood me.

    • Admin
      December 30th, 2009 at 17:35 | #11

      Hi, i’ve test my code with XAMPP 1.7.2 with php ver 5.3.0 and everything was perfect :)

      what php version u use?

      regards

  5. December 30th, 2009 at 18:09 | #12

    @admin:
    WampServer Version 2.0
    Php version 5.3.0

  6. Vlad
    May 12th, 2010 at 15:04 | #13

    If you can’t get this to work, you are a noob and shouldn’t be doing Web Development. Move aside and let the professionals fix your damn messes. Noobs….

  1. April 22nd, 2010 at 18:00 | #1