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.

Python Grammar - Rules and Expressions 1

Wordane | Python Grammar - Expressions and Rules


In order to get a valid Language with a certain logic, it is crucial to follow general rules. In English language we follow grammar, and similarly in any computer language. Computer languages cannot be ambiguous and verbose, hence they follow a strict grammar.
In this blog post, I discuss the Python grammar.

Generally in English, we follow the following rules AKA Backus Naur Form.

Rule 1: Subject -> Subject Verb Object

The Subject can be Noun, Object can be a Noun; hence

Rule 2: Subject -> Noun
Rule 3: Object -> Noun
Rule 4: Verb -> Like, Play, Dance ()
Further the Noun can be described as

Rule 5: Noun -> I, John Doe, Baseball

The purpose of Backus Naur Form is to precisely describe the language structure.
In general we follow

-> replacement (this can be sequence of Sentence, subject, Noun, Object, Verb or a )

is something that we are not finished with. i.e. Sentence, Subject, Object, Noun; but not Like, Play, Dance ()

In any language our goal is to start with Non-terminals and finish with terminals.

So, we start with
Sentence -> Subject Verb Object

Following the above rules 2 and 3
Sentence -> Noun Verb Noun
above is still a non-terminal, so we keep on going.

Sentence -> I Like Baseball
Above is a valid Expression in English

Following the same Grammar rules in English, the valid English expressions can be

I Play Baseball
John Doe Play Baseball
I Dance John Doe
Baseball Like John Doe

For Python, the grammar rule holds like so:

Rule 1: Expression -> Expression Operator Expression
Rule 2: Expression ->  Number
Rule 3: Operator -> +, * ...
Rule 4: Numbers -> 0,1 ...
Rule 5: Expression -> (Expression)

Starting with

Expression -> Expression Operator Expression
Expression -> Number Operator Number
Expression -> 1 + 1

Above is a valid Python Grammar

We can
Expression -> Expression Operator Expression

Now using the Rule 1:
Expression -> Expression Operator Expression Operator Expression

We can use Rule 1 and build complicated expressions. Continuing from above

Expression -> (Expression) Operator (Expression) Operator Expression

Expression -> (Number) Operator (Number) Operator Number

Expression -> (4) + (5) - 9
Above is a valid expression with all terminals, hence we cannot go further

Below are all valid expression
Expression -> 3
Expression ->  (1+ (2 * 3) - 5 + (4 * 20))
Expression -> (((((5)))))

Below are NOT valid expressions:
Expression -> - 55
For above Rule 1 is not followed}

Expression -> ((6)))
For above Rule 5 is not followed.

Expression -> )((6))
For above Rule 5 is not followed

Node.js - What is it ? Why to learn it ?

what is Nodejs? why to study nodejs ? how to study nodejs ? MEAN stack ? angularjs , expressjs, mongodb, mvc architecture, javascript, nosql database systems


Node.js is Javascript code running at the server-back-end, developed by Ryan Dahl in starting 2009, and is now maintained by Joyent. To execute javascript on the server, it needs to be interpreted and executed. Here comes Node.js ! By using Google's V8 VM, it executes the Javascript code at the server. Thus a run-time Javascript based environment is created by Google's V8 engine.

Node.js has many integrated modules. For eg : As you would need a Web listener for languages like PHP, and it would be Apache, Lighttpd or anything else. But you do not need that web listener with Node.js. When we install Node.js, many such libraries are imported, which helps us to couple the functionality within the application.

An application written in Node.js has basically two advantages [Author's view only :)]

1. The coding language is consistent i.e. We code in Javascript throughout. Server pages, Client pages, web-server pages, all are coded in Javascript. This makes the life of a developer relatively easy. Unlike otherwise, we would have to play with PHP / Python / Ruby on the server, and Javascript + Jquery + HTML on the client, with Apache / Lighttpd doing the web listener activities.

2. It becomes really tough for a developer when functionality like real time chat comes into picture. Not many years ago, functionality like these were a star wars like situation for a developer and the company with such features was a tremendous hit in the world [Remember Yahoo chat-rooms ? :)]. It required a team of Einstein - like developers to code for several months to bring out such a prototype, and eventually the code was tremendous amount of hacks ! With Node.js you can do the same on a Christmas eve ! In a nut-shell, with the advent of new standards of HTML web changed and brought in new features like web-sockets and many more, development became relatively very easy. Node.js has libraries which are revolutionizing the development cycle, and it is even growing bigger with people jumping with new libraries. Thus at the end of the day, you would code less and see more turn - about in your application. Not to forget that there is a great community to help, if you are stuck with the code !

If you Google about Node.js, you will notice that it uses 'Event-driven, non-blocking I/O, single-threaded event loops and asynchronous callbacks' model for doing the data-intensive real-time work.

Having said those fancy words, if you do not understand too much of it, do not trouble yourself too much. You will get it all as you start learning Node.js.

Node is often used with Expressjs, Angularjs, MongoDB. Together they combine to form a MEAN stack. Remember LAMP (linux, apache, mysql, php/python/perl) ?

Expressjs, is a open sourced lightweight framework for Node.js for organizing your code into MVC architecture and makes it even easier by integrating third party modules and various aspects into your web application. It reduces your code at least by 3x.

Angularjs is a Javascript framework maintained by Google available for free as a open source. Used for making browser based single-page applications (but it is not a constraint ! you can make multiple pages web app using angular), and maintaining the MVC architecture. Its purpose is to serve dynamic content through 2-way data binding and hence accomplishing automatic synchronization of the models. In short, it has the tools which will help you make a real time, single page web application.

Mongo DB is a NOSQL, document oriented database system. It has the added advantage of storing the JSON as-it-is into the database. Is a full featured database system, with the capabilities of load balancing, clustering and even acting as a file system.

Thus you see that even when we are using frameworks to make our work even easier, its all pure Javascript. Its not that you have to be a master in Javascript before learning Node, but you should be able to recognize Javascript code :)

At the end I would recommend learning Node.js, even if not for development but for fun. Its a whole new world of real time data delivery from the server to the browser.

Its no rocket science ! Its Node.js !

Tune in for the up-coming series for learning Node.js in a very simple way, the way I have learned it. I am no developer, neither I am a high end developer, I love to learn new technologies [and play with them, If I am able to grasp them :)] and I learned a bit of Node.js quickly. I will share it here in the upcoming posts.

Nodejs - Installation on RHEL / CentOs / Scientific Linux


Lately there has been a lot in Node.js. In this post I will install the dependencies of Node.js and then finally after installing I will run the "Hello World". Lets go.

Since I am using Red Hat Enterprise Linux Server release 6.5 on Amazon EC2 , hence the code and illustrations are applicable for RHEL / CentOS / Scientific Linux 6

I will install Nodejs along with Npm (Node Package Manager).

Step 1

Node.js and npm are available from the Fedora Extra Packages for Enterprise Linux (EPEL) repository. If your instance does not have it then, first download and enable EPEL.

To check if you have EPEL, run

sudo yum repolist

if you don't see epel, follow Step 2, else follow Step 3
(At the time of posting, the latest version is 6.8.)


Step 2 (optional, in case you do not have EPEL)

sudo su -c 'rpm -Uvh http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm'


Step 3

sudo yum install npm --enablerepo=epel

And that is it !
We are now ready with node with npm. Lets see what have we done so far.

To check the version of node type node -v in the command line.

To check the version of the npm , type npm -v in the command line.


Hello Node

Now, lets write our first node.js program
Open a terminal and do the following

node
console.log ("Hello Node");
Hello Node
undefined

and we have our Hello Node !


Exit Node

To quit the node prompt press ctrl + c two times on the terminal.

I hope this helps you in installing Nodejs on your RHEL / CentOS / Scientific Linux 6 box.

Hello World


This will be a place where I write something technical, few stories.