Viewed   561 times

I've just set up the new google recaptcha with checkbox, it's working fine on front end, however I don't know how to handle it on server side using PHP. I've tried to use the old code below but the form is sent even if the captcha is not valid.

$privatekey = "my key";
$resp = recaptcha_check_answer ($privatekey,

if (!$resp->is_valid) {
 $errCapt='<p style="color:#D6012C ">The CAPTCHA Code wasnot entered correctly.</p>';}



this is solution


    <title>Google recapcha demo - Codeforgeek</title>
    <script src=''></script>
    <h1>Google reCAPTHA Demo</h1>
    <form id="comment_form" action="form.php" method="post">
      <input type="email" placeholder="Type your email" size="40"><br><br>
      <textarea name="comment" rows="8" cols="39"></textarea><br><br>
      <input type="submit" name="submit" value="Post comment"><br><br>
      <div class="g-recaptcha" data-sitekey="=== Your site key ==="></div>


    $email; $comment; $captcha;


        echo '<h2>Please check the the captcha form.</h2>';

    $response = json_decode(file_get_contents(" SECRET KEY&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']), true);
    if($response['success'] == false)
        echo '<h2>You are spammer ! Get the @$%K out</h2>';
        echo '<h2>Thanks for posting comment.</h2>';

Monday, October 10, 2022

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

Wednesday, September 21, 2022

The simplest implementation:

  1. In your cshtml file (at the top)

    @section Scripts
        <script src=" site key"></script>
            grecaptcha.ready(function () {
                grecaptcha.execute('your site key', { action: 'homepage' }).then(function (token) {
                    document.getElementById("foo").value = token;
  2. In your cshtml, inside the form (just before </form>):

    <input type="hidden" id="foo" name="foo" />
  3. A function inside your Pagemodel class. See the documentation for the response object:

    public static bool ReCaptchaPassed(string gRecaptchaResponse)
        HttpClient httpClient = new HttpClient();
        var res = httpClient.GetAsync($" secret key no quotes&response={gRecaptchaResponse}").Result;
        if (res.StatusCode != HttpStatusCode.OK) 
            return false;
        string JSONres = res.Content.ReadAsStringAsync().Result;
        dynamic JSONdata = JObject.Parse(JSONres);
        if (JSONdata.success != "true" || JSONdata.score <= 0.5m)
            return false;
        return true;
  1. Finally, inside your OnPostAsync() handler, at the top:

    if (!ModelState.IsValid) 
        return Page();
        if (!ReCaptchaPassed(Request.Form["foo"]))
            ModelState.AddModelError(string.Empty, "You failed the CAPTCHA.");
            return Page();
Thursday, October 13, 2022

I share my code solution. But the proxy.php and other details with the full explanation (incl. backend part) you might find here.

Recaptcha with data-callback parameter

<script src="" >;
<form method="post">
<div class="g-recaptcha" data-sitekey="[site_key]" data-callback="onReturnCallback" data-theme="light"></div>
<input value="submit" type="submit" />

JS validation

<script src=""></script>
<script type="text/javascript">
var onReturnCallback = function(response) { 
    //alert('g-recaptcha-response: ' + grecaptcha.getResponse()); 
    var url='proxy.php?url=' + '';  
    $.ajax({ 'url' : url, 
               dataType: 'json',
               data: { response: response},
               success: function( data  ) {                     
                var res = data.success.toString();
                        alert( "User verified: " + res);                    
                if (res ==  'true') { 
                       document.getElementById('g-recaptcha').innerHTML = 'THE CAPTCHA WAS SUCCESSFULLY SOLVED'; 
                           } // end of success: 
         }); // end of $.ajax 
}; // end of onReturnCallback 


The backend part, proxy.php, is necessary because of security issue.

Friday, December 9, 2022

Have you tried loading the script before trying to send the request?

<script src=""></script>
<script type="text/javascript">
    var ReCaptchaCallbackV3 = function() {
        grecaptcha.ready(function() {
            grecaptcha.execute("site_key").then(function(token) {
                console.log("v3 Token: " + token);
Tuesday, November 1, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :