Prevent Bot attack in your site by using new Google reCAPTCHA

geordyjames profile image Geordy James ・2 min read

Nowadays there is an extensive increase in bot attacks and spams faced by our websites. But a web developer can easily prevent them by using reCAPTCHA in their form submission and login systems. One of the best and easy to integrate reCAPTCHA was by using google reCAPTCHA, a free service provided by google. The main advance of google reCAPTCHA is its look and feel and easy to use for visitors.

Now before we start coding we need to register our site and get a client key and secret key from google. You can register your site for free from Google. The registration process is fairly simple and straight forward so I am skipping it.

The client side integration is fairly easy
Paste this snippet before the closing tag on your HTML template:

<script src='https://www.google.com/recaptcha/api.js'></script>

Then Paste this snippet at the end of the

where you want the reCAPTCHA widget to appear:
<div class="g-recaptcha" data-sitekey="6LdV2ygTAAAAACZ2Js-_G6uLp99TEn0MUNpDPS3c"></div>

The server-side integration is a little tricky

you need to verify the client side response by sending it to https://www.google.com/recaptcha/api/siteverify and google will verify it and will return a JSON response.

It is tricky so what I do is call a function for HTTP call in above URL and JSON decode above response from google like below

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

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

 private function getHTTP($data)

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

 return $response;

You can download the complete code and library by visiting this link.


Editor guide