[php] How to Validate Google reCaptcha on Form Submit

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>

This question is related to php html recaptcha

The answer is


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>

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.


var googleResponse = $('#g-recaptcha-response').val();

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

    return false;
}

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


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";
    }

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 = 

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.


//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;
}

when using JavaScript it will work for me

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


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.


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.


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to recaptcha

Google Recaptcha v3 example demo How to hide the Google Invisible reCAPTCHA badge reCAPTCHA ERROR: Invalid domain for site key How can I validate google reCAPTCHA v2 using javascript/jQuery? ReCaptcha API v2 Styling Change New Google Recaptcha (v2) Width How to Validate Google reCaptcha on Form Submit Google reCAPTCHA: How to get user response and validate in the server side? How does Google reCAPTCHA v2 work behind the scenes? How to validate Google reCAPTCHA v3 on server side?