How to implement reCAPTCHA in PHP


CAPTCHA! yes it is spelt correct. It actually stands for
CAPTCHA => "Completely Automated Public Turing test to tell Computers and Humans Apart"

It was actually proposed by Alan Turing in 1950 to determine if a machine has a man equivalent mind.

A more generalist usage of the term and its concept is widely adopted to differentiate between a human and robot interaction on a website or a web application. This prevents headless browsing, spams, abuse and results in better user experience. Here we try to demonstrate how to integrate Google reCAPTCHA using PHP in simple steps.

Note: The version 1.0 of the Google captcha has been discontinued and has been renamed as reCAPTCHA which is v 2.0. Click here for more information.

Step 1 : Register the Domain

Go to the Google reCAPTCHA admin panel and register for keys on a particular domain, without any sub-directory.

Once you register your site on the admin panel; then you will be allocated the site keys. You can add multiple domains under one label, and can add multiple reCAPTCHA sites.

Step 2 : Get your Site API key

The site keys are under the "Keys" section.
There will be two keys
  • Site Key : Used in the HTML code on the domain
  • Secret Key : Used for communication between the site and the Google. As the name suggest, this has to be secret and has to be private.

Step 3 : Add HTML Code (index.php)

Add the script under the head section of the index.php (or index.html), like so,
<script src="https://www.google.com/recaptcha/api.js"></script>


Create a form with the div with class="g-recaptcha" and your site key, like so,
<html>
<html>
<head><title>How to use reCaptcha | Wordane</title>
<script src="https://www.google.com/recaptcha/api.js"></script>
</head>
<body> <!-- the body tag is required or the CAPTCHA may not show on some browsers -->
<!-- your HTML content -->
<form method="post" action="verify.php">
<label for="name">Name:</label>
<input name="name" required /><br/>
<label for="age">Age:</label>
<input name="age" required /><br/>
<!-- This is for the captcha and we get this from google.com/recaptcha/admin -->
<div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY_GOES_HERE"></div>
<input type="submit" />
</form>
<!-- more of your HTML content -->
</body>
</html>

Step 4 : Download reCAPTCHA library

To keep things simple in this example we will restrain from using composer. For a detailed installation of the reCAPTCHA visit the github repo on Google reCAPTCHA. If on linux (Ubuntu), then use the following to download the master branch as a zip in the working directory.

wget https://github.com/google/recaptcha/archive/master.zip

Then unzip it and rename (move) to a new directory for sake of sanity.

unzip master.zip
mv recaptcha-master/ captcha

The source contains a directory "src", which has all the namespaced classes under sub-directory ReCaptcha and autoload.php. We will use autoload.php, in order to avoid requiring any dependencies.

Step 5 : Add PHP code to verify user

As per our HTML form in Step 3, the action is specified to be verify.php, hence we create the file with the same name and require_once the autoload.php under the captcha/src/, like so

require_once('captcha/src/autoload.php');

The next step is to assign our Secret key from our reCAPTCHA admin dashboard as shown in Step 2 into a variable $privatekey, like so:
$privatekey = "YOUR_PRIVATE_KEY_GOES_HERE";

Now we create an object like so,
$recaptcha = new \ReCaptcha\ReCaptcha($privatekey);

Now we verify the private secret key with the response from the HTML form and remote address, like so
$resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER["REMOTE_ADDR"]);
When the HTML form is submitted at index.php (or index.html), then along with the form fields "g-recaptcha-response" is also send in POST.
The verify function needs the SERVER_ADDRESS and this response to verify.

Now we validate the response like so:
if ($resp->isSuccess()) {
        die('Thank you. Captcha verified correctly');
    } else {
        $errors = $resp->getErrorCodes();
        print_r($errors);
    }

Hence our verify.php would look something like this:
    require_once('captcha/src/autoload.php');
    $privatekey = "YOUR_PRIVATE_KEY_GOES_HERE";

    $recaptcha = new \ReCaptcha\ReCaptcha($privatekey);
    $resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER["REMOTE_ADDR"]);
    if ($resp->isSuccess()) {
        die('Thank you. Captcha verified correctly');
    } else {
        $errors = $resp->getErrorCodes();
        print_r($errors);
    }

Wordane | Google reCAPTCHA simplified

Conclusion

If the reCAPTCHA is filed in properly, along with properly, we see a "Thank you. Captcha verified correctly" message else we have an array with error codes and description.

For the working code of above example, click here for github repo
For a complete list of API request and response visit the Google documentation here.
For a complete introduction of the Google reCAPTCHA click here.

Object Oriented Programming - Classes vs Objects

Wordane : Classes vs Objects


Technology has evolved, and so has the way we make technological stuff. Programmers today often fall in the caveat of finding the multiple locations of the piece of code which needs to be updated. To avoid this we must follow a tenet DRY programming

DRY = Don't Repeat Yourself

Object-oriented programming is a style of coding that allows developers to group similar tasks into classes, thus making code easy to maintain and follow DRY. OOP might seem furious and intimidating at the start but is far more simpler than procedural or inline code.

Understanding Objects and Classes


The building blocks of OOP are Classes and Objects, but are not interchangeable terms. In our example lets take an example of a car and how we approach to build it.

Fig 1. Car Class

Classes

It is the blueprint for a concept. In the fig 1. above there is a blue print at the top, which is the class. It defines the basic layout of a Car (how it would look), even when there is no actual car. A car class defines a moving object on 4 typres (without size of tyres), steering, brake, acceleration.

Objects

It is the actual Car built according to the blueprint. In fig 1. we can see car objects to be the derivatives of Car Class in a way that it looks exactly the same, and may have additional individual properties of color, seats and tyre size. Thus all the car manufacturing companies, will follow the same Car Class blueprint, to make a car, however will add additional unique features, which make them unique from one another.

So we will have,
Fig 2. Car Class and Object definition
Hence we have a Basic Car Class, and each manufacturer has used the blueprint to create a unique car of its own. Multiple manufacturers can follow the blueprint of car class and create there own car. Each manufacturer can talk to other vendor.

What are Classes and Objects ? 

Classes = Structure of data and actions. 
Objects = Use the data and action in Classes to build themselves.

Hence, 
  • Object cannot exist without a Class. 
  • Multiple Objects can be created from one Class.
  • Objects are independent of each other. But can talk to each other.