65

Recently, Google completely overhauled their reCaptcha API and simplified it to a single checkbox.

reCaptcha

The problem is, I can submit a form with the reCaptcha included without checking it and the form will ignore the reCaptcha.

Before you had to send the form to a PHP file with the private key et al, but I'm not seeing any mention of that in their Developer's Guide. I have no idea how to validate the form to be sure the new reCaptcha was filled by the user.

Am I missing something? Is that PHP file with the private key still required?

All I have for the reCaptcha so far is:

<div data-type="image" class="g-recaptcha" data-sitekey="My Public Key"></div>

12 Answers 12

85

If you want to check if the User clicked on the I'm not a robot checkbox, you can use the .getResponse() function provided by the reCaptcha API.

It will return an empty string in case the User did not validate himself, something like this:

if (grecaptcha.getResponse() == ""){
    alert("You can't proceed!");
} else {
    alert("Thank you");
}

In case the User has validated himself, the response will be a very long string.

More about the API can be found on this page: reCaptcha Javascript API

7
  • what if I have multiple google recaptcha on a single page (multiple forms with goole recaptcha in each one), so how im going to validate it using your answer above? Commented Aug 26, 2015 at 4:53
  • 2
    @CodeDemon Check out this section of the API Documentation : developers.google.com/recaptcha/docs/display . In the examples you will see how multiple reCaptcha widgets are managed, each will have its own identifier, then you can call grecaptcha.getResponse(widget1);
    – Ali Bassam
    Commented Aug 26, 2015 at 20:31
  • 3
    What if someone wants to inject malicious data and creates a scripts that just sets grecaptcha.response != "" ?
    – cidadao
    Commented Aug 11, 2016 at 20:21
  • 2
    @msr client side validation is never enough, Google provides a way to validate the reCaptcha on the server side, please check the following : alibassam.com/how-to-use-googles-new-recaptcha-in-net
    – Ali Bassam
    Commented Aug 23, 2016 at 9:29
  • Its work for single google-recaptcha how can i validate for multiple google captcha in single Page ??? Commented Mar 20, 2017 at 9:18
21

You can verify the response in 3 ways as per the Google reCAPTCHA documentation:

  1. g-recaptcha-response: Once user checks the checkbox (I am not a robot), a field with id g-recaptcha-response gets populated in your HTML.
    You can now use the value of this field to know if the user is a bot or not, using the below mentioed lines:-

    var captchResponse = $('#g-recaptcha-response').val();
    if(captchResponse.length == 0 )
        //user has not yet checked the 'I am not a robot' checkbox
    else 
        //user is a verified human and you are good to submit your form now
    
  2. Before you are about to submit your form, you can make a call as follows:-

    var isCaptchaValidated = false;
    var response = grecaptcha.getResponse();
    if(response.length == 0) {
        isCaptchaValidated = false;
        toast('Please verify that you are a Human.');
    } else {
        isCaptchaValidated = true;
    }
    
    
    if (isCaptchaValidated ) {
        //you can now submit your form
    }
    
  3. You can display your reCAPTCHA as follows:-

    <div class="col s12 g-recaptcha" data-sitekey="YOUR_PRIVATE_KEY" data-callback='doSomething'></div>
    

    And then define the function in your JavaScript, which can also be used to submit your form.

    function doSomething() { alert(1); }
    

    Now, once the checkbox (I am not a robot) is checked, you will get a callback to the defined callback, which is doSomething in your case.

17

From a UX perspective, it can help to visibly let the user know when they can proceed to submit the form - either by enabling a disabled button, or simply making the button visible.

Here's a simple example...

<form>
    <div class="g-recaptcha" data-sitekey="YOUR_PRIVATE_KEY" data-callback="recaptchaCallback"></div>
    <button type="submit" class="btn btn-default hidden" id="btnSubmit">Submit</button>
</form>

<script>
    function recaptchaCallback() {
        var btnSubmit = document.getElementById("btnSubmit");

        if ( btnSubmit.classList.contains("hidden") ) {
            btnSubmit.classList.remove("hidden");
            btnSubmitclassList.add("show");
        }
    }
</script>
5
  • 1
    THIS! 100% THIS! I have been googling this for hours to get reCAPTCHA to work with my Zoho Web To Lead Form, and this works BEAUTIFULLY. THANK YOU!!!
    – Ken
    Commented Jul 29, 2017 at 18:57
  • This should be the accepted answer. The most simple application yet
    – LOTUSMS
    Commented Nov 30, 2017 at 15:46
  • Simple and elegant! Great answer! Thank you!
    – KyleBunga
    Commented Dec 28, 2017 at 9:45
  • I'm receiving this error on console. ReCAPTCHA couldn't find user-provided function: recaptchaCallback Commented Jan 18, 2018 at 10:50
  • 2
    This is good, but with a major caveat: the "disabled" or "hidden" can be easily override in the Dev Console or by a bot. We still have random form posts from bots which no doubt probably just edits the page to enable the button and submits it. All you need to do is remove the "disabled" tag from the HTML control, and you can click the "Submit" button.
    – Boyd P
    Commented Aug 1, 2019 at 0:15
16
var googleResponse = jQuery('#g-recaptcha-response').val();
if (!googleResponse) {
    $('<p style="color:red !important" class=error-captcha"><span class="glyphicon glyphicon-remove " ></span> Please fill up the captcha.</p>" ').insertAfter("#html_element");
    return false;
} else {            
    return true;
}

Put this in a function. Call this function on submit... #html_element is my empty div.

0
11

when using JavaScript it will work for me

<script src='https://www.google.com/recaptcha/api.js'></script>
<script>
function submitUserForm() {
    var response = grecaptcha.getResponse();
    if(response.length == 0) {
        document.getElementById('g-recaptcha-error').innerHTML = '<span style="color:red;">This field is required.</span>';
        return false;
    }
    return true;
}
 
function verifyCaptcha() {
    document.getElementById('g-recaptcha-error').innerHTML = '';
}
</script>
<form method="post" onsubmit="return submitUserForm();">
    <div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY" data-callback="verifyCaptcha"></div>
    <div id="g-recaptcha-error"></div>
    <input type="submit" name="submit" value="Submit" />
</form>

6

You can first verify in the frontend side that the checkbox is marked:

    var recaptchaRes = grecaptcha.getResponse();
    var message = "";

    if(recaptchaRes.length == 0) {
        // You can return the message to user
        message = "Please complete the reCAPTCHA challenge!";
        return false;
    } else {
       // Add reCAPTCHA response to the POST
       form.recaptchaRes = recaptchaRes;
    }

And then in the server side verify the received response using Google reCAPTCHA API:

    $receivedRecaptcha = $_POST['recaptchaRes'];
    $verifiedRecaptcha = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$google_secret.'&response='.$receivedRecaptcha);

    $verResponseData = json_decode($verifiedRecaptcha);

    if(!$verResponseData->success)
    {
        return "reCAPTCHA is not valid; Please try again!";
    }

For more info you can visit Google docs.

1
  • 1
    This should be the right answer, thx!
    – DarkteK
    Commented Nov 18, 2021 at 18:29
2

Try this link: https://github.com/google/ReCAPTCHA/tree/master/php

A link to that page is posted at the very bottom of this page: https://developers.google.com/recaptcha/intro

One issue I came up with that prevented these two files from working correctly was with my php.ini file for the website. Make sure this property is setup properly, as follows: allow_url_fopen = On

2

Verify Google reCapcha is valid or not after form submit

if ($post['g-recaptcha-response']) {
      $captcha = $post['g-recaptcha-response'];
      $secretKey = 'type here private key';
      $response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=" . $secretKey . "&response=" . $captcha);
        $responseKeys = json_decode($response, true);
        if (intval($responseKeys["success"]) !== 1) {
            return "failed";
        } else {
            return "success";
        }
    }
    else {
        return "failed";
    }
1
var googleResponse = $('#g-recaptcha-response').val();

if(googleResponse=='')
{   
    $("#texterr").html("<span>Please check reCaptcha to continue.</span>");

    return false;
}
0
//validate
$receivedRecaptcha = $_POST['recaptchaRes'];
$google_secret =  "Yoursecretgooglepapikey";
$verifiedRecaptchaUrl = 'https://www.google.com/recaptcha/api/siteverify?secret='.$google_secret.'&response='.$receivedRecaptcha;
$handle = curl_init($verifiedRecaptchaUrl);
curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false); // not safe but works
//curl_setopt($handle, CURLOPT_CAINFO, "./my_cert.pem"); // safe
$response = curl_exec($handle);
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
curl_close($handle);
if ($httpCode >= 200 && $httpCode < 300) {
  if (strlen($response) > 0) {
        $responseobj = json_decode($response);
        if(!$responseobj->success) {
            echo "reCAPTCHA is not valid. Please try again!";
            }
        else {
            echo "reCAPTCHA is valid.";
        }
    }
} else {
  echo "curl failed. http code is ".$httpCode;
}
0

One issue I came up with that prevented these two files from working correctly was with my php.ini file for the website. Make sure this property is properly set, as follows:

allow_url_fopen = 
0

While using Google reCaptcha with reCaptcha DLL file, we can validate it in C# as follows :

 RecaptchaControl1.Validate();
        bool _Varify = RecaptchaControl1.IsValid;
        if (_Varify)
        {
// Pice of code after validation.
}

Its works for me.

Not the answer you're looking for? Browse other questions tagged or ask your own question.