【问题标题】:Google reCaptcha validation (siteverify) returns falseGoogle reCaptcha 验证 (siteverify) 返回 false
【发布时间】:2017-12-09 19:03:28
【问题描述】:

之后我尝试实现一个简单的代码以在我的网站上使用 reCAPTCHA,但即使是这个简单的代码也不起作用。

问题是验证函数总是返回一个布尔值(假)。 我已经检查了几次密钥,但它们是正确的

<head>
 <script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
 <?php require_once "recaptchalib.php";  ?> 

    <?php
        if(isset($_POST['new_comment']) && !empty($_POST['new_comment'])):
            if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])) :

                $secret = "mysecretkey";

                    var_dump ($_POST['g-recaptcha-response']);

                $ip = $_SERVER['REMOTE_ADDR'];
                $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response'].'&remoteip='.$ip);

                    echo ("verifyresponse");
                    var_dump ($verifyResponse);

                $responseData = json_decode($verifyResponse, true);

                    echo ("responseData");
                    var_dump ($ResponseData);

                if ($response != null && $response->success) :

                    echo 'Form info successfully submitted';
                else:
                    $errMsg = 'Robot verification failed, please try again.';
                    echo $errMsg ;
                endif;
            else:
                $errMsg = 'Please click on the reCAPTCHA box.';
                echo $errMsg ;
            endif;
        else:
            $errMsg = '';
            $succMsg = '';
        endif;

        ?>

        <form name="form1" action="thisfile.php" method="post">
                    Enter Comment :<br />
                    <textarea name="new_comment" cols="75" rows="10"></textarea><br />
                    <div class="g-recaptcha" data-sitekey="mysitekey"></div>

                    <input type="submit" value="Envoyer" />
        </form>

</body>
</html>

var_dump ($_POST['g-recaptcha-response']) 给出了预期的长链字符,但 var_dump ($verifyResponse) 给出了 bool(false) 值,而我从未见过 var_dump ($ResponseData)

谁能帮我弄清楚这段代码有什么问题?

我已将问题缩小到file_get_content 调用返回“假”值而不是预期的事实

{ “成功”:是的, "challenge_ts": "2017-12-10T15:09:12Z", “主机名”:“我的域名” }

让我抓狂的是,如果回显完整的字符串并直接在浏览器中复制它,那么我会得到正确的答案(上图),所以我不知道出了什么问题......

这是我的代码的当前“精简”版本(我已经删除了 json_decode 调用以及之后的所有内容,因为只要我得到错误的返回值,我就知道其余的都行不通)

<!doctype html>
<html>
<head>
    <script src="https://www.google.com/recaptcha/api.js" async defer>
</script>
</head>
<body>
    <?php

        define('GOOGLE_RECAPTCHA_KEY','xxx');
        define('GOOGLE_RECAPTCHA_SECRET_KEY','yyy');

        $message = false;

      if ( isset( $_POST['new_comment'], $_POST['g-recaptcha-response'] ) && !empty( $_POST['new_comment'] ) && !empty( $_POST['g-recaptcha-response'] ) ){

      echo 'Sauvegarde du commentaire' ;
            $secret = GOOGLE_RECAPTCHA_SECRET_KEY;
            $ip = $_SERVER['REMOTE_ADDR'];
                            var_dump($_POST['g-recaptcha-response']);

            $getResponse = 'https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response'];
                            var_dump($getResponse);

            $GoogleResponse = file_get_contents($getResponse) ;
                            var_dump($GoogleResponse) ;

      }

    ?>

    <form method='post'>
        Enter Comment :<br />
        <textarea name='new_comment' cols='75' rows='10'></textarea>
        <?php
            if( !empty( $message ) )echo $message;
        ?>
        <br />
        <div class='g-recaptcha' data-sitekey='<?php echo GOOGLE_RECAPTCHA_KEY;?>'></div>
        <input type='submit' value='Envoyer' />
    </form>
</body>
</html>

【问题讨论】:

  • 我知道这听起来可能很愚蠢,但大概您实际上使用的是有效密钥而不是 $secret = "mysecretkey";?
  • 感谢您的提问。但实际上,我正在使用有效的密钥(用于密钥和数据站点密钥
  • 您能分享一下您在发布上述代码后所做的任何更改吗?

标签: php recaptcha


【解决方案1】:

检查变量:

if ($responseData!= null && $responseData['success']) {

对代码的其他修改:

$secret = "Add Your Secret Key"; // may be you are adding here public key instead of private ? check it
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$_POST['g-recaptcha-response']);
$response = json_decode($response, true); // if you add "true" then the response will be an array

if($response["success"] === true){
    echo "Form Submit Successfully.";
}else{
    echo "You are a robot";
}

另外我建议你看看这些教程:

Google Recaptcha Tutorial

还有这个来自 Github 的 recaptcha 示例:

require('/path/to/recaptcha/src/autoload.php');
$recaptcha = new \ReCaptcha\ReCaptcha($secret);
$resp = $recaptcha->verify($gRecaptchaResponse, $remoteIp);
if ($resp->isSuccess()) {
    // verified!
    // if Domain Name Validation turned off don't forget to check hostname field
    // if($resp->getHostName() === $_SERVER['SERVER_NAME']) {  }
} else {
    $errors = $resp->getErrorCodes();
}

Github link

【讨论】:

  • 其实我做不到。似乎对 json_decode 的调用永远不会返回。所以我在那之后做的任何事情都没有显示出来。
  • 您是否已将您的域添加到 google recaptcha 管理员? @弗兰克
  • 感谢凯维德。我已经添加了你的代码,但现在看来问题出在 http_build_query (显然代码的执行在那里停止)。您是什么意思“将我的域添加到 google recaptcha 管理员”?我已经注册了该站点以获取密钥;还有什么我应该做的吗?
  • 这就是问题所在:由于对 http_build_query 的调用没有返回,我无法测试错误代码。执行就停在那里,之后我在代码中添加的任何内容都会被忽略。
  • 好,我给你另一种方式
【解决方案2】:

我认为失败的原因如下。

第一个问题是使用true 作为json_encode 的第二个参数 - 这会将数据置于数组格式中,但您尝试使用 Object 语法访问返回的 json 字符串的 status 属性。

$responseData = json_decode($verifyResponse, true);

应该是这样的

$responseData = json_decode($verifyResponse);

第二期 - 这里是二合一。 $response 在哪里定义?而第二个就是上面提到的——使用对象语法而不是数组..

if ($response != null && $response->success)

应该是(假设$responseData = json_decode( $verifyResponse );

if ( $verifyResponse != null && $responseData->success==1 )

下面是我的测试 - 或多或少相同但旧版本的 php 所以使用花括号而不是冒号样式..

<!doctype html>
<html>
    <head>
        <script src="https://www.google.com/recaptcha/api.js" async defer></script>
    </head>
    <body>
        <?php

            define('GOOGLE_RECAPTCHA_KEY','xxxyyyzzz');
            define('GOOGLE_RECAPTCHA_SECRET_KEY','aaabbbccc');

            $message = false;

            if ( isset( $_POST['new_comment'], $_POST['g-recaptcha-response'] ) && !empty( $_POST['new_comment'] ) && !empty( $_POST['g-recaptcha-response'] ) ){

                $secret = GOOGLE_RECAPTCHA_SECRET_KEY;
                $ip = $_SERVER['REMOTE_ADDR'];
                $response = file_get_contents( 'https://www.google.com/recaptcha/api/siteverify?secret=' . $secret . '&response=' . $_POST['g-recaptcha-response'] . '&remoteip=' . $ip );
                $json = json_decode( $response );

                /* 
                    You need to use $json->success not $response->success 
                    and because you are trying to use object syntax rather
                    than array syntax json_decode does not need 2nd param `true`
                */
                if( $response && !is_null( $response ) && $json->success==1 ){
                    $message='Form info successfully submitted';
                }else{
                    $message = 'Robot verification failed, please try again.';
                }
            }
        ?>

        <form method='post'>
            Enter Comment :<br />
            <textarea name='new_comment' cols='75' rows='10'></textarea>
            <?php
                if( !empty( $message ) )echo $message;
            ?>
            <br />
            <div class='g-recaptcha' data-sitekey='<?php echo GOOGLE_RECAPTCHA_KEY;?>'></div>
            <input type='submit' value='Envoyer' />
        </form>
    </body>
</html>

【讨论】:

  • 谢谢,我试过你的代码。我最终遇到了同样的问题:调用后 json_decode 似乎永远不会返回...
猜你喜欢
  • 1970-01-01
  • 2016-08-24
  • 1970-01-01
  • 1970-01-01
  • 2012-05-06
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 2011-09-12
相关资源
最近更新 更多