如何在PHP表单中实现Google Recaptcha v3?

kik*_*les 3 php recaptcha contact-form recaptcha-v3

我想在Recaptcha的新版本(V3)中插入联系表格.

我已经寻找了不同的解决方案,但是它们只显示了部分代码,它们不完整或者我得到了一个错误,并且发现的大多数解决方案都非常复杂,因为它非常简单而且我不理解代码.

kik*_*les 15

我已经搜索了这个和其他论坛,在我的表单中实现了新版本的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>
Run Code Online (Sandbox Code Playgroud)

基本的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>
Run Code Online (Sandbox Code Playgroud)

基本的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
  //... Add code to filter access using $response . score
    if ($response.success==true && $response->score <= 0.5) {
        //Do something to denied access
    }
Run Code Online (Sandbox Code Playgroud)

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

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

    $secret = 'Your secret key here';
Run Code Online (Sandbox Code Playgroud)

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

    action = "your_action.php"
Run Code Online (Sandbox Code Playgroud)

  • Google需要有关reCaptcha的更详尽的文档。我花了几个小时试图弄清楚为什么我不能使它正常工作,只是发现他们没有提及为要添加的令牌添加隐藏的表单字段。 (2认同)