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

标签 php recaptcha contact-form recaptcha-v3

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

我寻找了不同的解决方案,但它们只显示了部分代码,它们不完整或者我得到了错误,而且找到的大多数解决方案对于如此简单的事情来说都非常复杂,而且我不理解代码。

最佳答案

我搜索了这个论坛和其他论坛,以在我的表单中实现新版本的 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 = json_decode(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
    }

您必须使用 $response->{'score'} 的值过滤访问。它可以取 0.0 到 1.0 之间的值,其中 1.0 表示用户与您网站的最佳交互,0.0 表示最差的交互(如机器人)。您可以在 ReCaptcha documentation 中看到一些使用示例.

您只需添加您的 key ,无需更多更改:

    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 ,在这个例子中:

    action = "your_action.php"

关于php - 如何以 PHP 形式实现 Google Recaptcha v3?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54183985/

相关文章:

javascript - 以/不以 + 开头的联系号码的正则表达式

php - 服务器端 session 安全吗?

javascript - 在 Aurelia 应用程序中使用 Google 的 reCAPTCHA

unit-testing - 使用 reCaptcha 测试表单提交的安全和标准方法是什么?

jquery - reCaptcha 字段按要求填写

PHP 联系表与网络解决方案

node.js - 使用 Nodemailer 的 Google 安全警报

php - 2 台云服务器,一名开发人员,一名生产人员;什么是好的部署流程?

php - 获得最多标记的帖子

php - 开闭原则——如何调用新版本?