验证recaptcha是否正确,PHP返回false

时间:2014-04-16 18:18:08

标签: php recaptcha

我正在尝试验证recaptcha是否正确,但它总是错误的,recaptcha_challenge_field和recaptcha_challenge_field在var_dump上始终为null。我正在使用代码中询问的公钥:

HTML:

<script type="text/javascript" src="http://www.google.com/recaptcha/api/challenge?
k=your_public_key_here"></script>
<noscript><iframe src="http://www.google.com/recaptcha/api/noscript?k=your_public_key_here"
height="300" width="500" frameborder="0"></iframe><br>
<textarea name="recaptcha_challenge_field" rows="3" cols="40">
</textarea>
<input type="hidden" name="recaptcha_response_field" value="manual_challenge">
</noscript>

我的php:

require_once('recaptchalib.php');
$privatekey = "**************************************";
$publickey = "**************************************";

$resp = recaptcha_check_answer(
    // $privatekey,
    $publickey, //changed this to public 
    $_SERVER["REMOTE_ADDR"],
    $_POST["recaptcha_challenge_field"],
    $_POST["recaptcha_response_field"]
);

var_dump($resp); 
var_dump($_POST["recaptcha_challenge_field"]);//null
var_dump($_POST["recaptcha_response_field"]); //null

if (!$resp->is_valid) {
    die( "The reCAPTCHA wasn't entered correctly. Go back and try it again." .
    "(reCAPTCHA said: " . $resp->error . ")" );
} else {
    die( "The reCAPTCHA is correct.");
}
$ resp上的

var_dump给了我:

object(ReCaptchaResponse)#610 (2) { ["is_valid"]=> bool(false) ["error"]=> string(21) "incorrect-captcha-sol"}

我在这里做错了什么?感谢。

2 个答案:

答案 0 :(得分:0)

如果有人围绕这个,我可以通过首先在js中序列化来访问php中的挑战和响应:

jQuery.fn.serializeObject = function(){
var o = {};
var a = this.serializeArray();
$.each(a, function() {
    if (o[this.name] !== undefined) {
        if (!o[this.name].push) {
          o[this.name] = [o[this.name]];
        }
    o[this.name].push(this.value || '');
    } else {
        o[this.name] = this.value || '';
    }
});
return o;
};

data = $("#myform").serializeObject();

答案 1 :(得分:0)

您需要将HTML位置放在表单标记中。

来自documentation

  <form action="" method="post">



    <script type="text/javascript"
       src="http://www.google.com/recaptcha/api/challenge?k=your_public_key">
    </script>
    <noscript>
       <iframe src="http://www.google.com/recaptcha/api/noscript?k=your_public_key"
           height="300" width="500" frameborder="0"></iframe><br>
       <textarea name="recaptcha_challenge_field" rows="3" cols="40">
       </textarea>
       <input type="hidden" name="recaptcha_response_field"
           value="manual_challenge">
    </noscript>



  </form>
相关问题