【问题标题】:ReCaptcha 2.0 With AJAXReCaptcha 2.0 与 AJAX
【发布时间】:2015-07-12 10:03:41
【问题描述】:

我已经设法让 ReCaptcha 2.0 在我的网站上运行。但是,它仅在我不使用 AJAX 并且让表单“自然”提交时才有效。

我想提交带有验证码的表单并用成功提示提醒用户不刷新页面

我尝试了以下代码,但似乎服务器没有得到用户响应:

HTML:

<form class="form" action="javascript:void(0)" novalidate>
    <!-- all the inputs... -->

    <!-- captcha -->
    <div class="input-group">
        <div class="g-recaptcha" data-sitekey="6LdOPgYTAAAAAE3ltWQGar80KUavaR-JblgPZjDI"></div>
    </div>

    <div class="errors" id="errors" style="display: none"></div>

    <div class="input-group">
        <input type="button" value="Send" class="btn-default right" id="submit">
        <div class="clear"></div>
    </div>
</form>

JS:

$('#submit').click(function(e) {
    console.log('clicked submit'); // --> works

    var $errors = $('#errors'),
        $status = $('#status'),

        name = $('#name').val().replace(/<|>/g, ""), // prevent xss
        email = $('#email').val().replace(/<|>/g, ""),
        msg = $('#message').val().replace(/<|>/g, "");

    if (name == '' || email == '' || msg == '') {
        valid = false;
        errors = "All fields are required.";
    }

    // pretty sure the problem is here
    console.log('captcha response: ' + grecaptcha.getResponse()); // --> captcha response: 

    if (!errors) {
        // hide the errors
        $errors.slideUp();
        // ajax to the php file to send the mail
        $.ajax({
            type: "POST",
            url: "http://orenurbach.com/assets/sendmail.php",
            data: "email=" + email + "&name=" + name + "&msg=" + msg + "&g-recaptcha-response=" + grecaptcha.getResponse()
        }).done(function(status) {
            if (status == "ok") {
                // slide down the "ok" message to the user
                $status.text('Thanks! Your message has been sent, and I will contact you soon.');
                $status.slideDown();
                // clear the form fields
                $('#name').val('');
                $('#email').val('');
                $('#message').val('');
            }
        });
    } else {
        $errors.text(errors);
        $errors.slideDown();
    }
});

PHP:

<?php
    // assemble the message from the POST fields

    // getting the captcha
    $captcha = '';
    if (isset($_POST['g-recaptcha-response']))
        $captcha = $_POST['g-recaptcha-response'];
    echo 'captcha: '.$captcha;

    if (!$captcha)
        echo 'The captcha has not been checked.';
    // handling the captcha and checking if it's ok
    $secret = 'MY_SECRET';
    $response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']), true);

    var_dump($response);

    // if the captcha is cleared with google, send the mail and echo ok.
    if ($response['success'] != false) {
        // send the actual mail
        @mail($email_to, $subject, $finalMsg);

        // the echo goes back to the ajax, so the user can know if everything is ok
        echo 'ok';
    } else {
        echo 'not ok';
    }
?>

PHP页面中的结果

captcha: The captcha has not been checked.array(2) { ["success"]=> bool(false) ["error-codes"]=> array(1) { [0]=> string(22) "missing-input-response" } } not ok

底线是,我怎样才能手动获取输入响应而不自动与其余的 POST 数据一起使用?

【问题讨论】:

  • 控制台中的grecaptcha.getResponse() 得到了什么?空吗?
  • @Samurai 是的。这就是我认为问题存在的原因。
  • 好吧,除非它被验证它返回空(没有回答或回答错误)。但是验证后你应该得到一个很长的字符串。
  • @Samurai 你是对的,在控制台中我确实得到了那个字符串,但似乎服务器没有得到它。即使我检查它也会给我一个missing-input-response 错误。
  • 奇怪,如果验证后发送到服务器,你不应该得到The captcha has not been checked位。

标签: javascript php jquery ajax recaptcha


【解决方案1】:

好吧,这很愚蠢。

我做错了几件事:

  • 在 PHP 文件中,所有字符串都带有单引号,这会导致问题。
  • 在整个测试过程中,我在 PHP 文件中添加了多个打印内容,因此 if (status == "ok") 始终无法正常工作。我确实收到了电子邮件,但没有得到我所做的任何确认,现在我明白了原因。
  • 当我想检查 PHP 文件遗漏了什么时,我只是在 URL 中找到它的地址,但总是出错。即使邮件已发送。现在我明白这不是检查日志的正确方法。

感谢@Samurai 帮助我解决问题。


最终的 PHP 代码:

<?php
    // assemble the message from the POST fields

    // getting the captcha
    $captcha = "";
    if (isset($_POST["g-recaptcha-response"]))
        $captcha = $_POST["g-recaptcha-response"];

    if (!$captcha)
        echo "not ok";
    // handling the captcha and checking if it's ok
    $secret = "MY_SECRET";
    $response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$captcha."&remoteip=".$_SERVER["REMOTE_ADDR"]), true);

    // if the captcha is cleared with google, send the mail and echo ok.
    if ($response["success"] != false) {
        // send the actual mail
        @mail($email_to, $subject, $finalMsg);

        // the echo goes back to the ajax, so the user can know if everything is ok
        echo "ok";
    } else {
        echo "not ok";
    }
?>

【讨论】:

  • 您能否在此处提供最终代码/标记以补充您自己的答案?
  • 刚刚登录,谢谢老兄!顺便说一句,在 php 代码中,在if 语句中的第一个echo "not ok"; 之后,您应该放置一个exit; 命令。
  • @joao_pimentel 为什么?
  • @Gofilord,如果我理解正确,如果没有来自客户端的验证码响应,即!$captcha 为真,则没有理由继续质疑服务器。
  • 您应该小心使用!= false 来验证 Google 的回复。 == true 在这里也同样有效,而且更安全。
猜你喜欢
  • 2016-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-19
  • 1970-01-01
相关资源
最近更新 更多