简体   繁体   中英

Ajax & Google reCaptcha

I'm trying to add reCaptcha to my resigration form on my website. I've followed a video tutorial on how to do it, however I'm struggling to adapt it to work with my form that use ajax to call a PHP file and does not actually submit the form. I've tried a few things suggested in previous questions, but none seem to get the intended result and instead display "I don't like robots" to the registration page. Some hints / suggestions would be nice if you can think of any.

<div class="g-recaptcha" data-sitekey="6LcXMg0UAAAAABmlDlOGa6onxqqzERZ483XOJbFm"></div>

Javascript

function Register(){
        var Forename = $("#txtForename" ).val();
        var Surname = $("#txtSurname" ).val();
        var Password = $("#txtPassword").val();
        var PasswordR = $("#txtPasswordR").val();
        var response = $("#g-recaptcha").val();
            $.post('functions/php/fncregister.php', {Forename: Forename, Surname: Surname, Password: Password, PasswordR: PasswordR, response: response}, function(data) {
                var returnValue = JSON.parse(data);
                if (returnValue['data'] == 0){
                    $('#mdlInfo').html('<p>Your account has been created under the username: <strong><span id="spnUsername">'+returnValue['username']+'</span></strong>. You <strong>must</strong> remember this as you will require it to log into your account.</p><p>Your account has also been added to a moderation que. <strong>You must wait until a member of staff activates your account!</strong></p>');
                    $("#mdlRegister").modal("show");
                }
                else if (returnValue['data'] == 1){
                    $('#divError').html('<p class="text-center text-danger bg-danger" id="pUPInc">Passwords did not match!</p>');
                }
                else if (returnValue['data'] == 3){
                    $('#divError').html('<p class="text-center text-danger bg-danger" id="pUPInc">An error occured when adding your details to the Database!</p>');
                }
                else if (returnValue['data'] == 4){
                    $('#divError').html('<p class="text-center text-danger bg-danger" id="pUPInc">I don\'t like Robots!</p>');
                }
            });
    }

PHP

<?php
//Retrieves variables from Javascript.
$Forename = $_POST["Forename"];
$Surname = $_POST["Surname"];
$Password = $_POST["Password"];
$PasswordR = $_POST["PasswordR"];

//reCaptcha
$Url = "https://www.google.com/recaptcha/api/siteverify";
$SecretKey = "---KEY---";
$Response = file_get_contents($Url."?secret=".$SecretKey."&response=".$_POST['response']."remoteip=".$_SERVER['REMOTE_ADDR']);
$Robot = json_decode($response);

$data = 0;

if(isset($Robot->success) AND $Robot->success==true){
    //OTHER CODE
}

else{
    //This code always runs (though this is only meant to happen if reCaptcha detects a robot.
    $data = 4;
        echo json_encode(["data"=>"$data"]);
?>

Here, it is important to watch casing of your variables:

$Response = file_get_contents($Url."?secret=".$SecretKey."&response=".$_POST['response']."remoteip=".$_SERVER['REMOTE_ADDR']);
//   because variables are case sensitive...
$Robot = json_decode($Response);  // it is $Response, not $response

If that doesn't fix it, please update your question with the output this produces:

$Response = file_get_contents($Url."?secret=".$SecretKey."&response=".$_POST['response']."remoteip=".$_SERVER['REMOTE_ADDR']);
die('Response file: <pre>'.$Response);
$Robot = json_decode($Response);

also try be sure to urlencode() the vars you are sending to google:

$Response = file_get_contents($Url."?secret=".urlencode($SecretKey)."&response=".urlencode($_POST['response'])."remoteip=".urlencode($_SERVER['REMOTE_ADDR']));

but by far, you must

$Robot = json_decode($Response);  // and NOT $response

here is a screenshot showing how to get the output from the ajax call where you have die() in your php processing said ajax call:

在此处输入图片说明

BEST SOLUTION

Review this guide on how to install Google reCAPTCHA with PHP

Not quite sure how I got it to work, but I did.

Firstly, I added a new variable "Response" into my Javascript and used the function listed in the documentation to retrieve the value of the key that is returned when the user proves they are not a robot. I added this variable into my AJAX call too, so that it is passed onto the PHP File, like so:

function Register(){
    var Forename = $("#txtForename" ).val();
    var Surname = $("#txtSurname" ).val();
    var Password = $("#txtPassword").val();
    var PasswordR = $("#txtPasswordR").val();
    var Response = grecaptcha.getResponse();
        $.post('functions/php/fncregister.php', {Forename: Forename, Surname: Surname, Password: Password, PasswordR: PasswordR, Response: Response}, function(data) {
            var returnValue = JSON.parse(data);
            if (returnValue['data'] == 0){
                $('#mdlInfo').html('<p>Your account has been created under the username: <strong><span id="spnUsername">'+returnValue['username']+'</span></strong>. You <strong>must</strong> remember this as you will require it to log into your account.</p><p>Your account has also been added to a moderation que. <strong>You must wait until a member of staff activates your account!</strong></p>');
                $("#mdlRegister").modal("show");
            }
            else if (returnValue['data'] == 1){
                $('#divError').html('<p class="text-center text-danger bg-danger" id="pUPInc">Passwords did not match!</p>');
            }
            else if (returnValue['data'] == 3){
                $('#divError').html('<p class="text-center text-danger bg-danger" id="pUPInc">An error occured when adding your details to the Database!</p>');
            }
            else if (returnValue['data'] == 4){
                $('#divError').html('<p class="text-center text-danger bg-danger" id="pUPInc">I don\'t like Robots!</p>');
            }
        });
}

In my PHP file I removed the user IP address from the URL post as it's optional according to documentation (not sure on the benefit of doing it though). Google then returns the information about the request and if successful then the item "success" with be true in my code and thus proceed onto generating the account:

$Url = "https://www.google.com/recaptcha/api/siteverify";
$SecretKey = "---KEY---";
$Response = file_get_contents($Url."?secret=".$SecretKey."&response=".$_POST['Response']);
$Robot = json_decode($Response);

$data = 0;

if(isset($Robot->success) AND $Robot->success==true){

I didn't use POST in the end, but used GET instead. I'm sure there's some security benefit as it will hide the secret key, so I will look into it shortly.

Thanks to @WEBjuju and my mate "Bridge Troll" for their assistance. I couldn't have done it without either of them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM