如何以PHP形式实现Google Recaptcha v3?

时间:2019-01-14 15:04:29

标签: php recaptcha contact-form recaptcha-v3

我想在Recaptcha的新版本(V3)中插入联系人。

我一直在寻找不同的解决方案,但是它们仅显示部分代码,它们不完整或出现错误,并且大多数解决方案对于非常简单的事情来说都是非常复杂的,我不理解代码。< / p>

2 个答案:

答案 0 :(得分:9)

我已经搜索了这个论坛和其他论坛,以在我的表单中实现ReCaptcha(V3)的新版本。 我需要知道如何:

  • 用JS插入
  • 如何使用PHP进行验证
  • 我的表单需要哪些新字段。

我没有找到任何简单的解决方案来显示所有这些要点,或者对于只想在他们的网站上插入联系表的人来说太复杂了。

最后,我采用了多个解决方案的一些代码部分,我使用了一个简单且可重用的代码,您只需要插入相应的键即可。

在这里。

基本JS代码

<script src="https://www.google.com/recaptcha/api.js?render=your reCAPTCHA site key here"></script>
<script>
    grecaptcha.ready(function() {
    // do request for recaptcha token
    // response is promise with passed token
        grecaptcha.execute('your reCAPTCHA site key here', {action:'validate_captcha'})
                  .then(function(token) {
            // add token value to form
            document.getElementById('g-recaptcha-response').value = token;
        });
    });
</script>

基本HTML代码

<form id="form_id" method="post" action="your_action.php">
    <input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">
    <input type="hidden" name="action" value="validate_captcha">
    .... your fields
</form>

基本的PHP代码

    if(isset($_POST['g-recaptcha-response'])){
        $captcha=$_POST['g-recaptcha-response'];
    }
    else
        $captcha = false;

    if(!$captcha){
        //Do something with error
    }
    else{
        $secret = 'Your secret key here';
        $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=
            .$secret.&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
        if($response.success==false)
        {
            //Do something with error
        }
    }
... The Captcha is valid you can continue with the rest of your code

您只需添加密钥,无需进行任何更改:

    src="https://www.google.com/recaptcha/api.js?render=your reCAPTCHA site key here"    
    grecaptcha.execute('your reCAPTCHA site key here'

    $secret = 'Your secret key here';

显然,在此示例中,您还必须更改表单的操作:

    action = "your_action.php"

答案 1 :(得分:0)

在上面的答案中,需要更新这些行才能读取 PHP 中的响应值:

    $response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']));

    $response->{'success'}

    $response->{'score'}
相关问题