获取Recapcha 2与PHP页面进行通信时出现问题

时间:2019-03-05 17:00:52

标签: javascript php html ajax recaptcha

我有一个输入字段表单,用于在服务器端通过验证来测试安装reCaptcha 2。我的流程图是通过Ajax将reCaptcha响应发布到PHP进行验证。我在console.log输出中得到的是,信息已正确捕获到通过ajax传输到PHP页面的字符串中。从服务器端我也可以正确捕获Post,但不能正确捕获gRecaptchaResponse。我的代码的相关部分如下:

HTML:

<form  action="php/recapcha.php" method="post" id="myForm">
    <div class="form-group">
    <label for="fullName">Name:</label>
    <input type="name" name="name" class="form-control" id="fullName" aria-describedby="namelHelp" placeholder="Enter Full Name">
    <small id="nameHelp" class="form-text text-muted">We'll never share your name with anyone else.</small>
   </div>
   <!--   Submit Recaptcha and Button    -->
    <div class="g-recaptcha mb-3" data-sitekey="myPublicKeyTqUf"></div>
            <button id="recaptcha-submit" type="submit" class="btn btn-primary"  value="">Submit</button>
            <div id="result" class="mt-3"><p id="serverMessages">Server Results:  <span id="serverResponseValue"></span></p></div>

</form>

jS的基本原理如下:

   <script type="text/javascript">

    function processForm() {

     if (grecaptcha === undefined) {
            alert('Recaptcha not defined'); 
            return; 
        }

    var response = grecaptcha.getResponse();

    if (!response) {
        alert('Could not get recaptcha response'); 
        return; 
        }

            var form = document.getElementById("myForm");   
            var action = form.getAttribute("action");
            var name = document.getElementById("fullName").value;
            var formString = 'name=' + name + '&gRecaptchaResponse' + response;

             console.log('formString: ' + formString);

            var xhr = new XMLHttpRequest();
            xhr.open('POST', action, true);
            xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
            xhr.onreadystatechange = function () {
              if(xhr.readyState == 4 && xhr.status == 200) {
                var result = xhr.responseText;  
                console.log('result: ' + result);


                var DataStr = JSON.stringify(result);

                var jsObjectResult = JSON.parse(DataStr);
                postResult(jsObjectResult);
              }
            };

          console.log('formString: ' + formString);
            xhr.send(formString);
          }

          button.addEventListener("click", function(event) {

            event.preventDefault();
            processForm();
          });

如您所见,我确保在客户端通过ajax将所有内容发送到php页面之前,通过JS函数获得reCaptcha响应。

这是我的PHP文件开头的摘要:

<?php
    header( 'Content-Type: application/json' );

function is_ajax_request() {
    return isset( $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] ) &&
        $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] == 'XMLHttpRequest';
} 

global $captcha;

    if ( isset( $_POST[ 'name' ] ) ) {
        $name = $_POST[ 'name' ];
        echo($name);
    } else {
        $name = '';
    }

    if(isset($_POST['gRecaptchaResponse'])){
          $captcha=$_POST['gRecaptchaResponse'];
        }
        if(!$captcha){
          echo '<h2>Please check the the captcha form.</h2>';
          exit($captcha);
        }
        $secretKey = "mySecretKeyUPzF9";
        $ip = $_SERVER['REMOTE_ADDR'];
        // post request to server
        $url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secretKey) . '&response=' . urlencode($captcha);
        $response = file_get_contents($url);
        $responseKeys = json_decode($response,true);
        // should return JSON with success as true
        if($responseKeys["success"]) {
               echo '<h2>Thanks for posting comment</h2>';
            exit;
        } else {
               echo '<h2>You are a spammer ! Get the @$%K out</h2>';
            exit;
}

因此,最重要的是。 google验证返回$ response == false,我收到消息“您是垃圾邮件发送者!获取@ $%K出去”,但在两个页面上均未检测到错误。

1 个答案:

答案 0 :(得分:1)

这就是我检查错误的方法。

if(isset($responseKeys["error-codes"])){
     //has errors
}
else{
     //no errors
}

另外合适的变量是 g-recaptcha-response ,而不是 gRecaptchaResponse