edokko
edokko

Reputation: 101

Google INVISIBLE reCaptcha + Bootstrap 4 validator

I've been working on online form, PHP Bootstrap 4 beta 2 validator with Google Invisible reCapture based on this site below.

https://shareurcodes.com/blog/google%20invisible%20recaptcha%20integration%20with%20php

But somehow I got error message says "An Error Occured and Error code is :missing-input"

I don't know what is wrong.

Here is my code...

signup.php

<? $config = require("config.php"); ?>

<html lang="en">
<head>
<link rel="stylesheet" href="css/bootstrap-v4.0.0-beta.2.css">

<script src="//code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<script type="text/javascript">
$(document).ready(function(){
    $('#needsValidation').validator().on('submit', function (e) {
      if (e.isDefaultPrevented()) {
        // handle the invalid form...
        console.log("validation failed");
      } else {
        // everything looks good!
        e.preventDefault();
        console.log("validation success");
        grecaptcha.execute();
      }
    });
}); 

function onSubmit(token){
    document.getElementById("needsValidation").submit();
};

</script>

</head>

<body>

<form class="container" method="post" action="signup_01.php" id="needsValidation" name="a_form" novalidate>

<div class="form-row">
                    <div class="col-md-6 mb-3">
                        <label for="name1">Your Name</label> <span class="red">*</span>
                        <input type="text" class="form-control" id="name1" name="name1" placeholder="Please enter Your Name *" required />

                        <div class="invalid-feedback">Your Name is required.</div>
                    </div>
</div>

<div id='recaptcha' class="g-recaptcha"
                      data-sitekey="<?php echo $config['client-key']; ?>"
                      data-callback="onSubmit"
                      data-size="invisible"></div>
                <button class="btn btn-block btn-custom" type="submit" onclick="return check_compare(); return true;">SIGNUP NOW!</button>

</form>


<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>

<script src="https://www.google.com/recaptcha/api.js" async defer ></script>

</body>
</html>

signup_01.php

<?php
require 'recaptcha.php';

$recaptcha = $_POST['g-recaptcha-response'];

$object = new Recaptcha();
$response = $object->verifyResponse($recaptcha);

if(isset($response['success']) and $response['success'] != true) {
    echo "An Error Occured and Error code is :".$response['error-codes'];
}else {
    echo "Correct Recaptcha";
}

recaptcha.php

<?php
class Recaptcha{

public function __construct(){
    $this->config = require('config.php');
}

public function verifyResponse($recaptcha){

    $remoteIp = $this->getIPAddress();

    // Discard empty solution submissions
    if (empty($recaptcha)) {
        return array(
            'success' => false,
            'error-codes' => 'missing-input',
        );
    }

    $getResponse = $this->getHTTP(
        array(
            'secret' => $this->config['secret-key'],
            'remoteip' => $remoteIp,
            'response' => $recaptcha,
        )
    );

    // get reCAPTCHA server response
    $responses = json_decode($getResponse, true);

    if (isset($responses['success']) and $responses['success'] == true) {
        $status = true;
    } else {
        $status = false;
        $error = (isset($responses['error-codes'])) ? $responses['error-codes']
            : 'invalid-input-response';
    }

    return array(
        'success' => $status,
        'error-codes' => (isset($error)) ? $error : null,
    );
}


private function getIPAddress(){
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) 
    {
    $ip = $_SERVER['HTTP_CLIENT_IP'];
    } 
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) 
    {
     $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } 
    else 
    {
      $ip = $_SERVER['REMOTE_ADDR'];
    }

    return $ip;
}

private function getHTTP($data){

    $url = 'https://www.google.com/recaptcha/api/siteverify?'.http_build_query($data);
    $response = file_get_contents($url);

    return $response;
    }
}

I know I can see value of my Client Key,

I think there is empty value on the this field "g-recaptcha-response" but I don't know how and what.

$recaptcha = $_POST['g-recaptcha-response'];

Would you please tell me how to make it work?

Thank you!

Upvotes: 4

Views: 1954

Answers (1)

Geordy James
Geordy James

Reputation: 2408

Replace your signup.php page with following codes. It works for me.

<? $config = require("config.php"); ?>

<html lang="en">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">


</head>

<body>

<form class="container" method="post" action="signup_01.php" id="needsValidation" name="a_form" novalidate>

<div class="form-row">
                    <div class="col-md-6 mb-3">
                        <label for="name1">Your Name</label> <span class="red">*</span>
                        <input type="text" class="form-control" id="name1" name="name1" placeholder="Please enter Your Name *" required />

                        <div class="invalid-feedback">Your Name is required.</div>
                    </div>
</div>

<div id='recaptcha' class="g-recaptcha"
                      data-sitekey="<?php echo $config['client-key']; ?>"
                      data-callback="onSubmit"
                      data-size="invisible"></div>
                <button class="btn btn-block btn-custom" type="submit" >SIGNUP NOW!</button>

</form>

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>

<!-- Boostrap Validator --> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.9/validator.min.js" ></script>

<script src="https://www.google.com/recaptcha/api.js" async defer ></script>

<script type="text/javascript">
$(document).ready(function(){
    $('#needsValidation').validator().on('submit', function (e) {
      if (e.isDefaultPrevented()) {
        // handle the invalid form...
        alert("validation failed");
      } else {
        // everything looks good!
        e.preventDefault();
        console.log("validation success");
        grecaptcha.execute();
      }
    });
}); 

function onSubmit(token){
    document.getElementById("needsValidation").submit();
};

</script>

</body>
</html>

You didn't add the bootstrap validator to your page. I add its CDN links too. Remember when you are developing something always open developer console to check javascript errors. And it is also recommended to use CDN for better performance and to move your js codes to bottom in the order of their dependencies.

Upvotes: 1

Related Questions