Search

Add CAPTCHA to Your Custom Form Without Using a Plugin

Listen to this article

CAPTCHA for SecurityThere are several WordPress plugins which provide the ability to add CAPTCHA to forms, on your site. Which is great. Because A) CAPTCHA prevents spam, and B) You don’t need to code anything. But when you are a developer, and in the need of adding CAPTCHA, in a custom form displayed by the plugin, you cannot rely on the availability of these plugins.

We came across this need, when we wanted to add a spam protection feature, to our custom plugin, Product Enquiry Pro for WooCommerce. Having a CAPTCHA is a great way to prevent spammers from flooding your mailbox with spam mails, or to prevent bots from accessing sensitive data.

 

Adding reCAPTCHA in Your Custom Form

Forms which provide access to confidential information, need solid spam protection. The reCAPTCHA provided by Google, provides a CAPTCHA service, to protect forms from malicious attacks. You might have surely come across one. Random skewed text is and displayed in an image. You have to read and enter the text, which is only possible for humans, to successfully submit the form.

reCAPTCHA Example

To add such a feature to custom form in your plugin, you will need to do the following:

  1. Option to Add API keys: The reCAPTCHA is a free service which you can avail using the reCAPTCHA API. You need to sign up at Google reCAPTCHA for your API keys. If your form has to display the reCAPTCHA, the user of the plugin needs to sign up for the service and use the received API keys. The plugin will provide an option to add and save the received public and private API keys.

  2. Using the PHP Library: For your WordPress plugin, you need to use the reCAPTCHA PHP library, which wraps around the API. The library allows easy integration of the CAPTCHA in your custom form.

    • Start by downloading the reCAPTCHA library, and add it in the same directory as your plugin.
    • You will need to add the following code in your form, to display the reCAPTCHA
require_once('recaptchalib.php');
$publickey = get_option( 'your_public_key' );
echo recaptcha_get_html($publickey);

where your_public_key, is the option to get the user’s public API key.

    • To validate the CAPTCHA, you have to add the following code in the form validation section of your plugin.
require_once('recaptchalib.php');
$privatekey = get_option( 'your_private_key' );
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
    // captcha mis-match, return an error
} else {
    // reCAPTCHA success, validate other fields.
}

where ‘your_private_key’ is the user’s private API key. Remember, such a CAPTCHA can slow down the display of your form. For more details refer the detailed documentation, for Using reCAPTCHA with PHP.

 

Adding a Simple Custom CAPTCHA to Your Form

A CAPTCHA is basically used to differentiate between humans and computers. This can be achieved by simpler means as well. For some forms, the reCAPTCHA might be an overkill, especially when you want visitors to fill the form, yet keep away spammers. The reCAPTCHA is fairly overcomplicated. For simpler, less sensitive forms, you can add a basic CAPTCHA. An uncomplicated CAPTCHA might be some simple mathematical equation, or random alphanumeric text. Including such a CAPTCHA is fairly simple. You can use session variables to check validate the result entered by the user.

Simple Math Captcha

To Add a Simple Mathematical CAPTCHA, you can use the below code:

  1. Generate the Equation and Save the Result: The below code will generate two random numbers, and create an addition or subtraction equation.

session_start();
$digit1 = mt_rand(1,20);
$digit2 = mt_rand(1,20);
if( mt_rand(0,1) === 1 ) {
    $math = "$digit1 + $digit2";
    $_SESSION['answer'] = $digit1 + $digit2;
} else {
    $math = "$digit1 - $digit2";
    $_SESSION['answer'] = $digit1 - $digit2;
}
  1. Display the Equation in your Form: You need to display the generated equation as part of your form.

<?php echo $math; ?> = <input name="answer" type="text" />
  1. Validate the Text Entered by the User: The final step is to validate whether the value entered by the user is correct, or not.

<?php
session_start();
if ($_SESSION['answer'] == $_POST['answer'] ) {
    // value entered is correct
}
else {
    // value is incorrect, kindly try again
}

 

And there you have it, a simple, yet effective CAPTCHA. But do note, many-a-times you must’ve observed, that the CAPTCHA text is usually in an image. This is because text placed in an image, is more difficult to crack, as compared to plain text. Do you have any questions regarding the above stated implementation? Or do you have any tips you’d like to share? Do leave your comments in the comment section below.

 

Aparna Gawade

Aparna Gawade

10 Responses

  1. Hi,
    thanks for a topic, but it is not working for me…..

    Could you please deliver full path of these files……I mean where should we put this code…

    Thanks…any help would be apreciate…

    1. Hi,

      Thank you for your comment. I do not have the file, but I can explain to you where to put the code. The part to generate the CAPTCHA and create the input field, should be added along with the rest of the code to create the form. If you are using a plugin to create the form, you need to check if the plugin provides a hook which you can use, to add this code.

      The second part, which is validation of the CAPTCHA field should be added in the PHP file where the form submission is handled. If the check is invalid, you should set an error (like you would for other fields on your form).

  2. hello i am getting an error like this

    Warning: require_once(‘recaptchalibphp’) [function.require-once]: failed to open stream: No such file or directory in /home/sonatech/public_html/sona/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php(373) : eval()’d code on line 2

    Fatal error: require_once() [function.require]: Failed opening required ‘‘recaptchalibphp’’ (include_path=’.:/usr/lib/php:/usr/local/lib/php’) in /home/sonatech/public_html/sona/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php(373) : eval()’d code on line 2

    1. Hi Manjot,
      You will need to download the reCAPTCHA Library, and add it in the same directory where you have added your PHP code. (In your case, it would be /home/sonatech/public_html/sona/wp-content/plugins/allow-php-in-posts-and-pages/).

  3. After two or three time login failed then want to show captcha on login page of WordPress, then what setting do, or need insert some code? please reply.

    1. Hi Rani,

      I haven’t tried this out. Seems like you need to register to the ‘wp_login_failed’ hook and then add the custom captcha.

  4. I need captcha without using any plugin for my site pinoytvshows for comments. Please gave me any better advice. Thanks

  5. First of all thank you for sharing this informative blog.. this blog really helpful for everyone.. explanation are clear so easy to understand… I got more useful information from this blog

    best php training

  6. Adding a Simple Custom CAPTCHA to Your Form . How do i place these codes in my html form which is saved as php.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get The Latest Updates

Subscribe to our Newsletter

A key to unlock the world of open-source. We promise not to spam your inbox.

Suggested Reads

How to Make Responsive Tables using CSS without Tag
WordPress Development

Custom WordPress Solutions, for You

LearnDash Development

Custom LearnDash Solutions, for You

WooCommerce Development

Custom WooCommerce Solutions, for You

WordPress Plugins

Scale your WordPress Business

WooCommerce Plugins

Scale your WooCommerce Business

LearnDash Plugins

Scale your LearnDash Business

Label

Title

Subtext

Label

Title

Subtext

Join our 55,000+ Subscribers

    The Wisdm Digest delivers all the latest news, and resources from the world of open-source businesses to your inbox.

    Suggested Reads