首页 > javascript > 问题获取Recapcha 2与PHP页面通信

问题获取Recapcha 2与PHP页面通信 (Problem Getting Recapcha 2 Communicating with the PHP Page)

问题

我有一个输入字段表单,我用它来测试在服务器端安装reCaptcha 2和验证。我的流程图是通过Ajax将reCaptcha响应发布到PHP进行验证。我在console.log输出中获得的是,信息被正确捕获到通过ajax传输到PHP页面的字符串中。我也从服务器端获得了正确捕获Posted但不是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();
          });

正如您所看到的,我确保在客户端通过JS函数获取reCaptcha响应,然后通过ajax将所有内容发送到php页面。

这是我的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;
}

所以,底线是。谷歌验证返回$ response == false,我收到消息“你是垃圾邮件发送者!获得@ $%K out”,两页都没有检测到错误。

解决方法

这是我检查错误的方法。

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

另外正确的变量是g-recaptcha-response而不是gRecaptchaResponse

问题

I have a one input field form which I am using to test installing reCaptcha 2 with verification on server-side. My flow chart is to post the reCaptcha response via Ajax to the PHP for verification. What I am getting on my console.log output is that the information is captured properly into the string that is being transmitted via ajax to the PHP page. I am also getting from the server-side that the Posted is captured properly but not the gRecaptchaResponse. Relevant parts of my codes are provided below:

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>

The basic of jS is as follows:

   <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();
          });

As you can see, I am making sure that on the client-side that I am getting a reCaptcha response via a JS function before sending everything out to the php page via ajax.

Here is a snippet of the beginning of my PHP file:

<?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;
}

So, the bottom line is. The google validation is returning $response == false and I am getting the message "You are a spammer! Get the @$%K out" with no error detected on the two pages.

解决方法

This is what I do for checking for errors.

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

Also the proper variable is g-recaptcha-response and not gRecaptchaResponse.

相似信息