THAT Agency Design Studio Blog

With all the captcha’s out there right now why would anyone reinvent the wheel and write another one. Well I did and here is why.

When I build forms, my go-to validation is 9 out of 10 times its jQuery plugin: Validation. Keeping with that and their built in functionality to basically = something to something. I used that to my advantage and use PHP to create a simple captcha.



How it works

Let’s start with what you will need. 1. A Form, 2. The PHP, 3. The jQuery. Cool we got that? let’s move on.

Lets begin with the simple PHP that builds the math

1
2
3
4
5
<?php
$randomNum = rand(0,9);
$randomNum2 = rand(0,9);
$randomNumTotal = $randomNum + $randomNum2;
?>

Here we are basically setting two different numbers (randomNum and randomNum2) and getting their total in (randomNumTotal). You can read up on the rand() php function, but basically what it’s doing here is giving me a random 1 digit number from 0-9.



Now we need to set up our jQuery pieces. so here is what you would need to include inside of your <head> tag.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="jquery.validate.min.js"></script>
<script type="text/javascript">
	$.validator.methods.equal = function(value, element, param) {
		return value == param;
	};
	$(document).ready(function(){
		$("#yourform").validate({
				rules: {
					lastName: "required",
					math: {
						equal: <?php echo $randomNumTotal; ?>	
					}
				},
				messages: {
					lastName: "*",
					math: "*"
				}
			});
	});
	</script>



Now with that javascript done, all we need to is create the form and style it up. Here is a really simple form with a person’s first name and last name and the captcha.

THE CSS

1
2
3
4
5
6
<style>
table td{height:30px;}
form label.error, label.error{color:red;padding:0 0 0 10px;}
input.error,select.error,textarea.error{border:1px solid red;}
.required {color:red; font-weight:bold;}
</style>



THE FORM

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<form action="" enctype="multipart/form-data" method="post" id="yourform">
<table cellpadding="0" cellspacing="0" border="0" width="500">
	<tr>
    	<td width="150" valign="top">First Name</td>
    	<td valign="top"><input name="firstName" id="firstName" type="text" size="25" maxlength="255"></td>
    </tr>
    <tr>
	    <td width="150" valign="top">Last Name</td>
		<td valign="top"><input name="lastName" id="lastName" type="text" size="25" maxlength="255"> <span class="required">*</span></td>
    </tr>
    <tr>
        <td width="150" valign="top" height="30">Security <input type="text" name="captchaImage" size="6" value="<?php echo $randomNum ?> + <?php echo $randomNum2 ?>" disabled="disabled" /></td>
        <td valign="top" height="30"><input type="text" name="math" id="math" size="6" maxlength="6" /> Please enter the correct result.</td>
    </tr>
    <tr>
        <td width="150">&nbsp;</td>
        <td valign="top"><input name="submit" type="submit" value="submit information" /></td>
    </tr>
</table>
</form>



And thats pretty much it. I would pressume that this can be changed for a bunch of other uses. maybe creating an array of the alphabet. selecting 1 letter, then the letter that follows and having the answer be the one after that (ex: A,B — answer: C). Or selecting two letters that are one letter apart and having the user select which one is in the middle (ex: A,C — answer: B).




-> Check out the live version of jQuery validate plugin plus PHP equals captcha




Well Here is the whole code for you. Remember it needs to be a PHP file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
# Set both random numbers you want to add
$randomNum = rand(0,9);
$randomNum2 = rand(0,9);
# Get the total.
$randomNumTotal = $randomNum + $randomNum2;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Using jQuery and PHP to create random addition problem as a captcha</title>
<style>
table td{height:30px;}
form label.error, label.error{color:red;padding:0 0 0 10px;}
input.error,select.error,textarea.error{border:1px solid red;}
.required {color:red; font-weight:bold;}
</style>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="jquery.validate.min.js"></script>
<script type="text/javascript">
	$.validator.methods.equal = function(value, element, param) {
		return value == param;
	};
	$(document).ready(function(){
		$("#yourform").validate({
				rules: {
					lastName: "required",
					math: {
						equal: <?php echo $randomNumTotal; ?>	
					}
				},
				messages: {
					lastName: "*",
					math: "*"
				}
			});
	});
	</script>
</head>
<body>
<p>Example of using jQuery and PHP to create random addition problem as a captcha</p>
<br/>
<form action="" enctype="multipart/form-data" method="post" id="yourform">
<table cellpadding="0" cellspacing="0" border="0" width="500">
	<tr>
    	<td width="150" valign="top">First Name</td>
    	<td valign="top"><input name="firstName" id="firstName" type="text" size="25" maxlength="255"></td>
    </tr>
    <tr>
	    <td width="150" valign="top">Last Name</td>
		<td valign="top"><input name="lastName" id="lastName" type="text" size="25" maxlength="255"> <span class="required">*</span></td>
    </tr>
    <tr>
        <td width="150" valign="top" height="30">Security <input type="text" name="captchaImage" size="6" value="<?= $randomNum ?> + <?= $randomNum2 ?>" disabled="disabled" /></td>
        <td valign="top" height="30"><input type="text" name="math" id="math" size="6" maxlength="6" /> Please enter the correct result.</td>
    </tr>
    <tr>
        <td width="150">&nbsp;</td>
        <td valign="top"><input name="submit" type="submit" value="submit information" /></td>
    </tr>
</table>
</form>
</body>
</html>

Share this article

15 Responses to "jQuery validate plugin plus PHP equals captcha"

  1. Slick! BTW, you can use Microsoft’s CDN to deliver the tasty Validate plugin: http://ajax.microsoft.com/ajax/jquery.validate/1.5.5/jquery.validate.min.js

    Just sayin’ :P

  2. Thanks Jesse, that would be nice as well. let them take the load. lol.

    Great addition. thanks.

  3. thats a really badly designed captcha as the solution to the captcha is within the html page on which the captcha sits. Far better would be have the solution stored server side, or, if you must store the solution client side have it stored as a hash of the solution that can then be compared with a hash of the users solution.

  4. Hey Phil. Thanks for your comment. This post was meant as a conceptual idea more than a new method. With all the captcha “solutions” out there, its hard to pick which one to use or which ones would really work.

    I do like your idea on hashing the values though. I would love to see what others come up with in this matter. As I said in my post, I presume that this could be changed for more uses. With that being said; by all means, evolve this concept.

  5. Hey Rich! First of all thanks a lot for this easy script of validation it made my life so much easier but i have a question. I got a site built with a news feed that and in each newsfeed people are allowed to comment so each form has its own form that get’s created dynamically. Any idea’s on how to make this validation to check which form your in? any ideas?
    Any help i can get is much appreciated many thanks in advance

  6. Hey John,

    So a page could have 4 articles and in each article, you have a different form for comments?

    Is that the gist of it?

  7. Hi there,
    i just want to know how can i submit form through image not a submit button.
    i have tries lot of time with different trick using javascript: submit() but its not working.
    thanks

  8. How would you make the email validate as a valid email address? ie validate against
    (/^[^\\W][a-zA-Z0-9\\_\\-\\.]+([a-zA-Z0-9\\_\\-\\.]+)*\\@[a-zA-Z0-9_]+(\\.[a-zA-Z0-9_]+)*\\.[a-zA-Z]{2,4}$/)

  9. Thank you gor this info . is there other areas to bypas captchas? I’d like to learn that..

  10. kane, You can use the validate plugin and it has a built in email validator.

  11. Hey,

    Love the concept, but your custom equal method doesn’t seem to follow the proper syntax that is displayed in the documentation. Could you please explain how this works?

    Thanks

  12. @marcellos I am not sure I follow.

  13. thanks very good explanation and useful resource. Long live JQuery! :-)

  14. If you wanted to remove all your validation and link to an external file that has it, and use remote: “captcha.php”; to bring in the math function how do you set the rule for it to equal the total of the captcha.php file? captcha.php is just the randommath function. making it equal:$randommath doesn’t work. I can get the input to populate with random numbers but the solutions don’t work. any idea?

  15. Thanks so much. Great little script!

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Copyright ©2006-2010 THAT Agency, LLC, a web design firm and web develelopment company. All Rights Reserved.
Partner website: THAT SEO Agency