Getting Null in g-recaptcha-response Google's reCaptcha

前端 未结 2 1590
南笙
南笙 2021-01-25 22:21

I am trying to implement Google\'s reCaptcha v.2.0 but i am getting null in g-recaptcha-response due to this reCaptcha is not working properly and I am always g

相关标签:
2条回答
  • 2021-01-25 22:56

    I'm not sure how you're submitting the form without an actual submit button, but I've copy/pasted your code and it works for me. I did change the error arrays into echo to display the else messages.

    <!DOCTYPE html>
    <html>
        <head>
            <script src="https://www.google.com/recaptcha/api.js"></script>
        </head>
        <body>
            <form action="" method="POST">
                <div class="g-recaptcha" style="margin-left: 230px; margin-top: 40px;" data-sitekey="Your-Public-Site-Key"></div>
    
                <input type="submit" name="submit" value="Post comment">
            </form>
        </body>
    </html>
    
    <?php
    
        if( isset($_POST['submit']) ) {
            if( isset($_POST['g-recaptcha-response']) && !empty( $_POST['g-recaptcha-response'] ) ) {
    
                //your site secret key
                $secret = 'Your-Private-Site-Key';
    
                //get verify response data
                $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
    
                $responseData = json_decode($verifyResponse);
    
                if($responseData->success) {
    
                    // My All Logic Here
                    echo 'Success Message';
                }
                else {
                    echo 'Robot verification failed, please try again.';
                } 
            }
            else {
                echo 'Please click on the reCAPTCHA box.';
            }
        }
    ?>
    
    0 讨论(0)
  • 2021-01-25 23:13

    I've run into the same issue. The strangest part is a client-side call to grecaptcha.getResponse() returns to correct response. For some reason it's just not setting g-recaptcha-response. So my workaround was to set a data-callback function to populate a hidden field with the response and use that server-side instead. The hidden input also helps with ease of client-side validation.
    eg:

    <div class="g-recaptcha" data-callback="captcha_onclick" data-sitekey="######"></div>
    <input type="hidden" name="recaptcha" id="recaptchaValidator" />
    

    javascript:

    function captcha_onclick() {
        document.getElementById('recaptchaValidator').value = grecaptcha.getResponse();
    }
    

    server-side:

    if(!empty($_POST['recaptcha'])) {
        $captcha = $_POST['recaptcha'];
        ...
    }
    
    0 讨论(0)
提交回复
热议问题