Skip to main content
Blog / Making a Simple Math Captcha using both jQuery and PHP
jQuery

Making a Simple Math Captcha using both jQuery and PHP

Making a Simple Math Captcha using both jQuery and PHP

I wanted to write a simple Captcha that I could easily integrate into my own scripts that would work with or without Javascript. My first approach was to find open-source that I could pretty much just copy and paste into my code with little modification. All the cookie-cutter Captcha scripts I found were so bloated with extra code and were either only client-side (Javascript) or server-side (PHP), that I decided to create something from scratch. What I came up with is a script that uses Ajax for a smoother user experience (no browser reload on submit), but also works if the user has Javascript disabled for progressive enhancement (or graceful degradation).

Dependencies: jQuery, jQuery Validation Plugin and jQuery Placeholder Plugin
Assumptions: Understands jQuery and PHP, and has used jQuery Validation Plugin. Note: This tutorial is written for developers and only explains the captcha portion. I don’t go into other workings of the form, ie: Ajax submit, error handling, etc.

Captcha Field

The following code section goes into your HTML form to create the Captcha section. To set the values of the fields to be added, use PHP rand() function to get a different random value each time the page is loaded (1st number is random number 1-4, and 2nd number is random number from 5-9 for easy use).

[php htmlscript=”true”]

(Are you human, or spambot?)
[/php]

Define custom method for Validation Plugin

Method basically gets the random values from the form, the total value entered by the user, adds them together and compares. If the two numbers don’t equal the total, then it returns an error. Otherwise it returns the result.

[js]
$.validator.addMethod(‘captcha’,
function(value) {
$result = ( parseInt($(‘#num1’).val()) + parseInt($(‘#num2’).val()) == parseInt($(‘#captcha’).val()) ) ;
$(‘#spambot’).fadeOut(‘fast’);
return $result;
},
‘Incorrect value, please try again.’
);
[/js]

Call custom validation method defined above

The highlighted sections are the relevant parts to the Captacha. The rest is doing error handling for the other form fields.

[js]
$(‘#contact’).validate({
debug: false,
rules: {
message: {
required: true,
minlength: 10,
maxlength: 255
},
captcha: {
required: true,
captcha: true
}
},
messages: {
firstName: “First name field required.”,
lastName: “Last name field required.”,
email: {
required: “Email address required”,
email: “Email address must be in the format name@domain.com.”
},
message: {
required: “Message field required”,
minlength: “Message must contain at least 10 characters.”,
maxlength: “Message must not contain more than 255 characters.”
},
chkCaptcha: {
required: “* Required”
}
}
});
[/js]

Server side handler (PHP) in case Javascript is disabled

Now we have to handle captcha if Javascript is disabled. Since the captcha values are generated using PHP, we can retrieve those from the POST array.

[php]
$num1 = isset($_POST[‘num1’]) ? $_POST[‘num1’] : “”;
$num2 = isset($_POST[‘num2’]) ? $_POST[‘num2’] : “”;
$total = isset($_POST[‘captcha’]) ? $_POST[‘captcha’] : “”;
[/php]

Define a Captcha function and call the function

[php]
function captcha_validation($num1, $num2, $total) {
global $error;
//Captcha check – $num1 + $num2 = $total
if ( intval($num1) + intval($num2) == intval($total) ) {
$error = null;
}
else {
$error = “Captcha value is wrong.”;
}
return $error;
}
$captcha_error = captcha_validation($num1, $num2, $total);
[/php]

Now Captcha can be validated with your other form variables. You can see a working demo here, or download it from the link below (contains all the code and dependent files).

Download from my GitHub page: https://github.com/laithsinawi/php-jquery-simple-math-captcha

Ready to talk about your site?

Free consultation, no pressure — just a conversation.

Get a Free Quote
LS
Written by Laith Sinawi
Laith Sinawi is the founder of Sinawi Web Design, building custom WordPress sites for small businesses across Sonoma, Marin, and Napa Counties since 2011. He works directly with every client — no account managers, no handoffs.
Recent posts
WooCommerce vs Shopify: Which Is Better? (2023 Comparison)
When it comes to choosing an e-commerce platform, two of the most popular options are WooCommerce and Shopify. Both platforms have their own unique features and benefits, but which one is better? In this post, we’ll take a look at the pros and cons of each platform and help you decide which one is right […]
Read More →
Top 6 SEO Best Practices to Improve Your Organic Rankings
I often get this question from clients: “How can I improve my SEO?” My response typically emphasizes that it’s a substantial and ongoing endeavor rather than a simple task.  So, here’s my comprehensive list of steps to help you get an understanding of the project scope and ultimately improve your website’s search engine optimization (SEO): […]
Read More →
5 Essential Tips on How to Find a Good Web Designer for Your Business Needs
When it comes to creating a website for your business, finding the right web designer is crucial. A skilled web designer can ensure that your website not only looks great, but that it also functions smoothly, is easy to navigate, and effectively communicates your brand’s message. But with so many web designers out there, how […]
Read More →
WordPress vs Squarespace – Which has better SEO?
If you’re looking to build a website for your business, it’s important to understand the importance of search engine optimization (SEO) to attract potential customers. In this article, we’ll explore two popular platforms, WordPress vs Squarespace, and how they compare in terms of their SEO capabilities. WordPress is a flexible content management system that provides […]
Read More →