03
Aug

Code tip: Adding a google reCAPTCHA to your form

  • Font size: Larger Smaller
  • Hits: 48302
  • Print

The calcbuilder form already includes an invisible spam filter to avoid robots from sending your calculator forms, but if you want to increase security you may want to add a google reCAPTCHA field. This code tip will show you the needed steps.

First, you need to get a Google reCAPTCHA site key and a secret key. You can find more detais here:

reCAPTCHA: Getting started

Once you have the pair of keys you can start building your form. The calculator form should be built normally, and you also need to add at the 'form layout' an specific section where we will place the google reCAPTCHA widget. We'll add to the form:

<div id="html_element"> </div>

Please note we've used the id 'html_element' but you can change for any other identifier you prefer, you only need to ensure you keep using the same id within the following code.

At the js tab 'Write directly at HTML page', you need to add:

<script type="text/javascript">
var onloadCallback = function() {

grecaptcha.render('html_element', {
'sitekey' : 'YOUR_SITE_KEY_HERE'
});
};
</script>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>

This way the widget will be added to your page, now we need to 'validate' user input in order to return calculator values normally or to abort execution.

At the 'code' section, we'll add

//verify captcha
$recaptcha_secret = "YOUR_RECAPTCHA_SECRET_HERE";

$postdata = http_build_query(
array(
'secret' => $recaptcha_secret,
'response' => $_POST['g-recaptcha-response']
)
);

$peer_key = version_compare(PHP_VERSION, '5.6.0', '<') ? 'CN_name' : 'peer_name';
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded\r\n',
'content' => $postdata,
'verify_peer' => true,
$peer_key => 'www.google.com',
)
);

$context = stream_context_create($opts);

$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify",false,$context);
$responsejson=$response;
$response = json_decode($response, true);
if($response["success"] === true)

{ $result="Logged In Successfully";

//YOU CAN ADD THE DEFAULT CALCULATOR FUNCTIONS HERE

}
else
{
//Validation failed, you can write a message
$result= "You are a robot";

//or, abort execution with the following line
exit -1;
}

Your Google reCAPTCHA validator is now ready, you can try it at the front-end, when 'calculate' button is used, you will see the normal calculator output if user passes validation, or a custom/empty result otherwise



Last modified on
Trackback URL for this blog entry.
FaLang translation system by Faboba

Our clients' feedback