如何在服务器端验证 Google reCAPTCHA v3


How to validate Google reCAPTCHA v3 on server side?

我刚刚设置了新的带有复选框的谷歌验证码,它在前端工作正常,但是我不知道如何使用PHP在服务器端处理它。我尝试使用下面的旧代码,但即使验证码无效,表单也会发送。

require_once('recaptchalib.php');
$privatekey = "my key";
$resp = recaptcha_check_answer ($privatekey,
        $_SERVER["REMOTE_ADDR"],
        $_POST["recaptcha_challenge_field"],
        $_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
 $errCapt='<p style="color:#D6012C ">The CAPTCHA Code wasnot entered correctly.</p>';}

私钥安全

虽然这里的答案肯定有效,但他们使用的是GET请求,这会暴露您的私钥(即使使用了https)。在谷歌开发者上,指定的方法POST

有关更多详细信息:https://stackoverflow.com/a/323286/1680919

通过开机自检进行验证

function isValid() 
{
    try {
        $url = 'https://www.google.com/recaptcha/api/siteverify';
        $data = ['secret'   => '[YOUR SECRET KEY]',
                 'response' => $_POST['g-recaptcha-response'],
                 'remoteip' => $_SERVER['REMOTE_ADDR']];
                 
        $options = [
            'http' => [
                'header'  => "Content-type: application/x-www-form-urlencoded'r'n",
                'method'  => 'POST',
                'content' => http_build_query($data) 
            ]
        ];
    
        $context  = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return json_decode($result)->success;
    }
    catch (Exception $e) {
        return null;
    }
}
数组语法

:我使用"新"数组语法[]而不是array(..))。如果您的 php 版本还不支持此功能,则必须相应地编辑这 3 个数组定义(请参阅注释)。

返回

值:此函数返回true用户是否有效,如果无效,则返回false,如果发生错误则返回null。例如,您只需编写if (isValid()) { ... } <</p>

div class="answers"即可使用它>这是

解决方案

索引.html

<html>
  <head>
    <title>Google recapcha demo - Codeforgeek</title>
    <script src='https://www.google.com/recaptcha/api.js'></script>
  </head>
  <body>
    <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>
    </form>
  </body>
</html>

验证.php

<?php
    $email; $comment; $captcha;
    if(isset($_POST['email']))
        $email=$_POST['email'];
    if(isset($_POST['comment']))
        $comment=$_POST['comment'];
    if(isset($_POST['g-recaptcha-response']))
        $captcha=$_POST['g-recaptcha-response'];
    if(!$captcha){
        echo '<h2>Please check the the captcha form.</h2>';
        exit;
    }
    $response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=YOUR SECRET KEY&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']), true);
    if($response['success'] == false)
    {
        echo '<h2>You are spammer ! Get the @$%K out</h2>';
    }
    else
    {
        echo '<h2>Thanks for posting comment.</h2>';
    }
?>

http://codeforgeek.com/2014/12/google-recaptcha-tutorial/

我不喜欢这些解决方案中的任何一个。我改用这个:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
    'secret' => $privatekey,
    'response' => $_POST['g-recaptcha-response'],
    'remoteip' => $_SERVER['REMOTE_ADDR']
]);
$resp = json_decode(curl_exec($ch));
curl_close($ch);
if ($resp->success) {
    // Success
} else {
    // failure
}

我认为这是优越的,因为您确保它被 POST 到服务器并且它不会发出尴尬的"file_get_contents"呼叫。这与此处描述的 recaptcha 2.0 兼容:https://developers.google.com/recaptcha/docs/verify

我觉得这更干净。我看到大多数解决方案都是file_get_contents的,当我觉得卷曲就足够了。

简单和最好的解决方案如下。
索引.html

<form action="submit.php" method="POST">
   <input type="text" name="name" value="" />
   <input type="text" name="email" value="" />
   <textarea type="text" name="message"></textarea>
   <div class="g-recaptcha" data-sitekey="Insert Your Site Key"></div>
   <input type="submit" name="submit" value="SUBMIT">
</form>

提交.php

<?php
if(isset($_POST['submit']) && !empty($_POST['submit'])){
  if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
    //your site secret key
    $secret = 'InsertSiteSecretKey';
    //get verify response data
    $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
    $responseData = json_decode($verifyResponse);
    if($responseData->success){
        //contact form submission code goes here
        $succMsg = 'Your contact request have submitted successfully.';
    }else{
        $errMsg = 'Robot verification failed, please try again.';
    }
  }else{
    $errMsg = 'Please click on the reCAPTCHA box.';
  }
}
?>

我从这里找到了这个参考和完整的教程 - 使用新的谷歌 reCAPTCHA 与 PHP

我喜欢Levit的答案,最终使用了它。但我只是想指出,以防万一,有一个官方的谷歌PHP库用于新的reCAPTCHA:https://github.com/google/recaptcha

最新版本(现在为 1.1.2)支持 Composer,并包含一个示例,您可以运行该示例以查看是否已正确配置所有内容。

下面您可以看到此官方库附带的部分示例(为清楚起见,我进行了一些小修改):

// Make the call to verify the response and also pass the user's IP address
    $resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
    if ($resp->isSuccess()) {
// If the response is a success, that's it!
        ?>
        <h2>Success!</h2>
        <p>That's it. Everything is working. Go integrate this into your real project.</p>
        <p><a href="/">Try again</a></p>
        <?php
    } else {
// If it's not successful, then one or more error codes will be returned.
        ?>
        <h2>Something went wrong</h2>
        <p>The following error was returned: <?php
            foreach ($resp->getErrorCodes() as $code) {
                echo '<tt>' , $code , '</tt> ';
            }
            ?></p>
        <p>Check the error code reference at <tt><a href="https://developers.google.com/recaptcha/docs/verify#error-code-reference">https://developers.google.com/recaptcha/docs/verify#error-code-reference</a></tt>.
        <p><strong>Note:</strong> Error code <tt>missing-input-response</tt> may mean the user just didn't complete the reCAPTCHA.</p>
        <p><a href="/">Try again</a></p>
    <?php
    }

希望它对某人有所帮助。

使用 PHP 在服务器端进行验证。您需要考虑的两件最重要的事情。

1. $_POST['g-recaptcha-response']
2.$secretKey = '6LeycSQTAAAAAMM3AeG62pBslQZwBTwCbzeKt06V';
$verifydata = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secretKey.'&response='.$_POST['g-recaptcha-response']);
        $response= json_decode($verifydata);

如果你$verifydata真的你就完成了
欲了解更多信息,请查看此
使用 PHP 的谷歌验证码 |只有 2 步集成

在上面的示例中。对我来说,这if($response.success==false)的事情是行不通的。这是正确的PHP代码:

$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "--your_key--";
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if (isset($data->success) AND $data->success==true) {
            // everything is ok!
} else {
            // spam
}

与 mattgen88 类似,但我只是修复了CURLOPT_HEADER,并重新定义了数组,以便在 domain.com 主机服务器中工作。 这个在我的 XAMPP 本地主机上不起作用。那些小错误,但花了很长时间才弄清楚。此代码已在 domain.com 主机上进行了测试。

   $privatekey = 'your google captcha private key';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
    curl_setopt($ch, CURLOPT_HEADER, 'Content-Type: application/json');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, array(
        'secret' => $privatekey,
        'response' => $_POST['g-recaptcha-response'],
        'remoteip' => $_SERVER['REMOTE_ADDR']
    )
               );
    $resp = json_decode(curl_exec($ch));
    curl_close($ch);
    if ($resp->success) {
        // Success
        echo 'captcha';
    } else {
        // failure
        echo 'no captcha';
    }

这里有一个简单的例子。只要记得提供来自谷歌API的secretKey和siteKey。

<?php
$siteKey = 'Provide element from google';
$secretKey = 'Provide element from google';
if($_POST['submit']){
    $username = $_POST['username'];
    $responseKey = $_POST['g-recaptcha-response'];
    $userIP = $_SERVER['REMOTE_ADDR'];
    $url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey&remoteip=$userIP";
    $response = file_get_contents($url);
    $response = json_decode($response);
    if($response->success){
        echo "Verification is correct. Your name is $username";
    } else {
        echo "Verification failed";
    }
} ?>
<html>
<meta>
    <title>Google ReCaptcha</title>
</meta>
<body>
    <form action="index.php" method="post">
        <input type="text" name="username" placeholder="Write your name"/>
        <div class="g-recaptcha" data-sitekey="<?= $siteKey ?>"></div>
        <input type="submit" name="submit" value="send"/>
    </form>
    <script src='https://www.google.com/recaptcha/api.js'></script>
</body>

源教程链接

谷歌重新验证码V2

步骤1 - 转到谷歌验证码

登录,然后获取站点密钥和密钥

步骤2 - 在此处下载PHP代码并在服务器上上传src文件夹。

步骤3 - 在表单中使用以下代码.php

        <head>
            <title>FreakyJolly.com Google reCAPTCHA EXAMPLE form</title>
            <script src='https://www.google.com/recaptcha/api.js'></script>
        </head>
        <body>
            <?php
            require('src/autoload.php');
            $siteKey = '6LegPmIUAAAAADLwDmXXXXXXXyZAJVJXXXjN';
            $secret = '6LegPmIUAAAAAO3ZTXXXXXXXXJwQ66ngJ7AlP';
            $recaptcha = new 'ReCaptcha'ReCaptcha($secret);
            $gRecaptchaResponse = $_POST['g-recaptcha-response']; //google captcha post data
            $remoteIp = $_SERVER['REMOTE_ADDR']; //to get user's ip
            $recaptchaErrors = ''; // blank varible to store error
            $resp = $recaptcha->verify($gRecaptchaResponse, $remoteIp); //method to verify captcha
            if ($resp->isSuccess()) {
               /******** 
                Add code to create User here when form submission is successful
               *****/
            } else {
                /****
                // This variable will have error when reCAPTCHA is not entered correctly.
                ****/
               $recaptchaErrors = $resp->getErrorCodes(); 
            }

            ?>
                <form autcomplete="off" class="form-createuser" name="create_user_form" action="" method="post">
                    <div class="panel periodic-login">
                        <div class="panel-body text-center">
                            <div class="form-group form-animate-text" style="margin-top:40px !important;">
                                <input type="text" autcomplete="off" class="form-text" name="new_user_name" required="">
                                <span class="bar"></span>
                                <label>Username</label>
                            </div>
                            <div class="form-group form-animate-text" style="margin-top:40px !important;">
                                <input type="text" autcomplete="off" class="form-text" name="new_phone_number" required="">
                                <span class="bar"></span>
                                <label>Phone</label>
                            </div>
                            <div class="form-group form-animate-text" style="margin-top:40px !important;">
                                <input type="password" autcomplete="off" class="form-text" name="new_user_password" required="">
                                <span class="bar"></span>
                                <label>Password</label>
                            </div>
                            <?php 
                                    if(isset($recaptchaErrors[0])){
                                        print('Error in Submitting Form. Please Enter reCAPTCHA AGAIN');
                                    }
                              ?>
                            <div class="g-recaptcha" data-sitekey="6LegPmIUAAAAADLwDmmVmXXXXXXXXXXXXXXjN"></div>
                            <input type="submit" class="btn col-md-12" value="Create User">
                        </div>
                    </div>
                </form>
        </body>
        </html>

针对@mattgen88的回答,这里是一个排列更好的CURL方法:

   //$secret= 'your google captcha private key';
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL             => "https://www.google.com/recaptcha/api/siteverify",
        CURLOPT_HEADER          => "Content-Type: application/json",
        CURLOPT_RETURNTRANSFER  => true,
        CURLOPT_SSL_VERIFYPEER  => FALSE, // to disable ssl verifiction set to false else true
        //CURLOPT_ENCODING      => "",
        CURLOPT_MAXREDIRS       => 10,
        CURLOPT_TIMEOUT         => 30,
        CURLOPT_HTTP_VERSION    => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST   => "POST",
        CURLOPT_POSTFIELDS      => array(
            'secret' => $secret,
            'response' => $_POST['g-recaptcha-response'],
            'remoteip' => $_SERVER['REMOTE_ADDR']
        )
    ));
    $response = json_decode(curl_exec($curl));
    $err = curl_error($curl);
    curl_close($curl);
    if ($response->success) {
        echo 'captcha';
    } 
    else if ($err){
        echo $err;
    }   
    else {
        echo 'no captcha';
    }

检查以下示例

<script src='https://www.google.com/recaptcha/api.js'></script>
<script>
function get_action(form) 
{
    var v = grecaptcha.getResponse();
    if(v.length == 0)
    {
        document.getElementById('captcha').innerHTML="You can't leave Captcha Code empty";
        return false;
    }
    else
    {
         document.getElementById('captcha').innerHTML="Captcha completed";
        return true; 
    }
}
</script>
<form autocomplete="off" method="post" action=submit.php">
    <input type="text" name="name">
    <input type="text" name="email">
    <div class="g-recaptcha" id="rcaptcha"  data-sitekey="site key"></div>
    <span id="captcha" style="color:red" /></span> <!-- this will show captcha errors -->
    <input type="submit" id="sbtBrn" value="Submit" name="sbt" class="btn btn-info contactBtn" />
</form>