如何在表单提交上验证Google reCaptcha

时间:2023-01-17 13:20:11

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

最近,谷歌彻底彻底检查了他们的reCaptcha API,并将其简化为一个复选框。

如何在表单提交上验证Google reCaptcha

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

问题是,我可以提交包含reCaptcha的表单而不检查它,表单将忽略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.

在您必须使用私钥等将表单发送到PHP文件之前,我在他们的开发人员指南中没有看到任何提及。我不知道如何验证表单以确保用户填写新的reCaptcha。

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

我错过了什么吗?是否仍需要具有私钥的PHP文件?

All I have for the reCaptcha so far is:

到目前为止我所有的reCaptcha都是:

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

10 个解决方案

#1


56  

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.

如果要检查用户是否单击了“我不是机器人”复选框,则可以使用reCaptcha API提供的.getResponse()函数。

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

有关API的更多信息,请参见此页面:reCaptcha Javascript API

#2


13  

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.

把它放在一个函数中。在提交时调用此函数... #html_element是我的空div。

#3


11  

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

您可以根据Google reCAPTCHA文档以3种方式验证回复:

  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:-

    g-recaptcha-response:一旦用户选中了复选框(我不是机器人),就会在HTML中填充一个带有id g-recaptcha-response的字段。您现在可以使用此字段的值来了解用户是否是机器人,使用下面的mentioed行: -

    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:-

    您可以按如下方式显示您的reCAPTCHA: -

    <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.

    然后在JavaScript中定义该函数,该函数也可用于提交表单。

    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.

    现在,一旦选中了复选框(我不是机器人),您将获得对定义的回调的回调,在您的情况下是doSomething。

#4


6  

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


2  

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

请尝试以下链接: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

该页面的最新页面发布了该页面的链接: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

我提出的一个阻止这两个文件正常工作的问题是我的网站php.ini文件。确保正确设置此属性,如下所示:allow_url_fopen = On

#6


1  

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:

然后在服务器端使用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.

有关详细信息,您可以访问Google文档。

#7


0  

When using Google reCaptcha with reCaptcha DLL file then we can validate in C#.

当使用带有reCaptcha DLL文件的Google reCaptcha时,我们可以在C#中进行验证。

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

Its work for me.

它的工作对我来说。

#8


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

#9


0  

Verify Google reCapcha is valid or not after form submit

表单提交后,验证Google reCapcha是否有效

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

#10


-1  

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

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

    return false;
}

#1


56  

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.

如果要检查用户是否单击了“我不是机器人”复选框,则可以使用reCaptcha API提供的.getResponse()函数。

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

有关API的更多信息,请参见此页面:reCaptcha Javascript API

#2


13  

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.

把它放在一个函数中。在提交时调用此函数... #html_element是我的空div。

#3


11  

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

您可以根据Google reCAPTCHA文档以3种方式验证回复:

  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:-

    g-recaptcha-response:一旦用户选中了复选框(我不是机器人),就会在HTML中填充一个带有id g-recaptcha-response的字段。您现在可以使用此字段的值来了解用户是否是机器人,使用下面的mentioed行: -

    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:-

    您可以按如下方式显示您的reCAPTCHA: -

    <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.

    然后在JavaScript中定义该函数,该函数也可用于提交表单。

    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.

    现在,一旦选中了复选框(我不是机器人),您将获得对定义的回调的回调,在您的情况下是doSomething。

#4


6  

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


2  

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

请尝试以下链接: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

该页面的最新页面发布了该页面的链接: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

我提出的一个阻止这两个文件正常工作的问题是我的网站php.ini文件。确保正确设置此属性,如下所示:allow_url_fopen = On

#6


1  

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:

然后在服务器端使用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.

有关详细信息,您可以访问Google文档。

#7


0  

When using Google reCaptcha with reCaptcha DLL file then we can validate in C#.

当使用带有reCaptcha DLL文件的Google reCaptcha时,我们可以在C#中进行验证。

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

Its work for me.

它的工作对我来说。

#8


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

#9


0  

Verify Google reCapcha is valid or not after form submit

表单提交后,验证Google reCapcha是否有效

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

#10


-1  

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

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

    return false;
}