Monday, 24 September 2018

Setting Up Recaptcha 2.0 with JavaScript and PHP


reCAPTCHA need to verify bots (automatic system) can't take advantage of your site. reCAPTCHA 2.0 is somewhat different than the old reCAPTCHA. In version 1.0 it required to type text but now in 2.0 it’s simply a click of a button as below image.

The term of verifying front end users is a bit different. A variable named "g-recaptcha-response" is sent through a POST request to your server-side script, and along with your reCAPTCHA secret key that you get when you sign up for your website, you need to pass that secret key along to Google to tell that the user is a bot or not to determine by system. The response from Google is a JSON response on success for failure both case, so that we will be using file_get_contents() and json_decode() to fetch and parse the response and decide that front user is valid or not.

The below is just a HTML form you should create to see captcha in your desired page. The div element with the class of "g-recaptcha" is the element where we want to place our Google captcha (reCAPTCHA). You need to replace data-sitekey with the key you get from google when you sign up for reCAPTCHA (https://www.google.com/recaptcha/intro/index.html).
<form method="post" enctype="multipart/form-data">
    <div class="g-recaptcha" data-sitekey="YOUR_KEY"></div>
    <button type="submit">CHECK RECAPTCHA</button>
</form>
But I will show another technique how to show reCAPTCHA using JavaScript. Below is a simple script to show how you can integrate reCAPTCHA using JavaScript. But server side validation using PHP. Use need to create an div with ID (suppose, you can create your div with other ID) captcha_container
<script src='https://www.google.com/recaptcha/api.js'></script>

var captchaContainer = grecaptcha.render('captcha_container', {
    'sitekey' : 'Your sitekey',
    'callback' : function(response) {
        console.log(response);
    }
});
Now time to validate reCAPTCHA from server side.
<?php
$url = 'https://www.google.com/recaptcha/api/siteverify';

$data = array(
    'secret' => 'YOUR_SECRET',
    'response' => $_POST["g-recaptcha-response"]
);

$options = array(
    'http' => array(
        'method' => 'POST',
        'content' => http_build_query($data)
    )
);

$context = stream_context_create($options);
$verify = file_get_contents($url, false, $context);
$captcha_success = json_decode($verify);

if ($captcha_success->success == false) {
    echo "<p>You are a bot! Go away!</p>";
}
else if ($captcha_success->success == true) {
    echo "<p>You are not not a bot!</p>";

0 comments:

Post a Comment