How To Integrate Google reCAPTCHA v2 Into Your PHP Website

Category
Tutorial
Reading
5 mins
Views
1.4K
Posting
04 Aug 2022

Before this captcha service existed, usually website owners used a verification method by matching some random strings into the server. Currently, this method is obsolete and is no longer used. There is an effective and simple method, namely by using a captcha service. Captcha is one method to protect websites that is quite easy to implement, the installation process is easy and accompanied by guaranteed security from hacker attacks or irresponsible people.

When it comes to websites, security is a very important thing to pay attention to, especially when it comes to spamming and bots. Spamming or bots often occur by websites that have several forms to be processed by the server, moreover these forms do not have strict security. Usually the perceived impact is quite disturbing and can make the server overload traffic. Therefore, website owners or developers usually apply captcha as a solution to this problem.

Actually, many services offer captcha to protect your website, but here we suggest using a captcha service from Google, namely reCAPTCHA, the reason is quite simple, this service is very easy to use and the security system is high. This method is often used in CRUD-based applications using PHP or other programming languages.

 

install Google reCAPTCHA 2.0 On Your Website Easily

 

 

1. What is Google reCAPTCHA

Google reCAPTCHA is a verification method to prove that the user is a human, not a bot or automatic script. In simple terms, this method will prevent repeated requests from any kind of bot or spamming, namely by matching multiple images for verification. This will make your website much more secure.

Therefore, this method is commonly used to secure forms such as logins, registers, blog comments, reviews from bot attacks or spam.

This service supports various modern browsers such as Chrome, Mozilla, Safari, Edge, Opera and others. And you need to know, this service has 3 versions including:

1. reCAPTCHA Enterprise

First launched in 2020, which provides services to users to protect against scams and can be integrated into mobile/mobile applications using API services.

2. reCAPTCHA v3

This service was launched in 2018, a service that will protect websites from spam, scams by verifying with certain methods and providing action on every incoming request.

3. reCAPTCHA v2

This service is the second version and is quite popularly used by websites around the world to protect the forms on their sites, first launched in 2014 which serves to verify every user when making requests to the server, by ticking I am not a robot on the widget.

This time we will provide a tutorial on how to integrate this service into a PHP application using reCAPTCHA v2.

 

2. Getting the reCAPTCHA API Key

There are two important keys in this service, namely the secret key and the site key. The secret key is used as an authentication token into the service to get a response from the Google API, then the site key is used to integrate with the destination website to display a special widget.

To get these two keys, you must first register your website on https://www.google.com/recaptcha, this is very important so that the captcha widget appears on your website page.

1. Labels

Fill in whatever label you want, this label is the project name of the reCAPTCHA from your website.

2. reCAPTCHA type

For type, you can just match it by selecting the type v2 and I'm not a robot checkbox.

3. Domains

Fill in the domain name according to the domain name to be registered, for the choice of the domain itself, you can register more than one domain. And please note not to use https or http prefix, just fill it with example.com only.

After that check the terms of services and click the submit button. And you have managed to get the secret key and site key.


3. Google reCAPTCHA integration with website

After getting the secret key and site key, the first thing to do is to add a special Javascript library to HTML. Otherwise, the captcha widget will not appear. The widget in question is like this:

Put the required Javascript libraries right before the closing body . tag

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

After that, add the special HTML code below to save the site key into your web page form:

<div class="g-recaptcha" data-sitekey="paste your site key here!"></div>

You can put this HTML code anywhere as long as it's still in the form tag. Please note, this HTML code is very important, because it is to store and send code from the user to the server, which will later be sent to the Google API for checking.

Example of the full version:

<form id="form" action="verify_recaptcha.php" method="POST">
  <div class="g-recaptcha" data-sitekey="blablablabla"></div>
  <input type="Submit" name="Submit">
</form>

 

4. Validate verification status in Google reCAPTCHA

Next we will verify into the Google API using PHP. At this stage, the server will fetch the captcha code from the user and send it to the Google API for checking.

To receive a response from the Google API, you can use two methods, namely cURL or file_get_contents, just choose what you want. Please create a new file and name it verify_recaptcha.php and copy and paste the code below:

1. Using file_get_contents

The following is an example of implementing API validation using the file_get_contents method:

<?php

if (!empty($_POST["g-recaptcha-response"])) {
    $generate_code = $_POST["g-recaptcha-response"];
    $secret = "Copy paste your secret key here!";
    $verify = file_get_contents(
        "https://www.google.com/recaptcha/api/siteverify?secret=" .
            $secret .
            "&response=" .
            $generate_code
    );
    $response = json_decode($verify);

    if ($response->success) {
        $message = "Successfully verified";
    } else {
        $message = "Failed to verify";
    }
    echo $messages;
}


2. Using cURL

The following is an example of implementing API validation using the cURL method:

<?php

if (!empty($_POST["g-recaptcha-response"])) {
    $generate_code = $_POST["g-recaptcha-response"];
    $secret = "COPY PASTE YOUR SECRET KEY HERE!";

    $data = [
        "secret" => $secret,
        "response" => $generate_code,
    ];

    $verify = curl_init();
    curl_setopt(
        $verify,
        CURLOPT_URL,
        "https://www.google.com/recaptcha/api/siteverify"
    );
    curl_setopt($verify, CURLOPT_POST, true);
    curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($verify, CURLOPT_RETURNTRANSFER, true);
    $jsonresponse = curl_exec($verify);
    $response = json_decode($jsonresponse);

    if ($response->success) {
        $message = "Successfully verified";
    } else {
        $message = "Failed to verify";
    }

    echo $messages;
}

The way this service works is quite simple, the server will send the required data into the Google API and then receive the request and send the response to your server.

The results of the response will indicate whether the verification process has been successful or not, this response will be given in the form of a boolean (true or false) in the key success array, if the response given is true, then the reCAPTCHA inputted by the user has been successfully processed, and vice versa.

And Google reCAPTCHA has also been successfully integrated with your website pages.

 

Conclusion

This Google reCAPTCHA service can be used for any purpose to protect your website pages from spamming and bots such as login pages, contacts, registers, blog comments and much more.

Share