Using reCaptcha with PHP

Posted on Sun 07 December 2014 in Tutorials • 3 min read

I got lazy with a couple of development projects and didn't add any form of protection to some web contact forms I'd created. As you can imagine, it didn't take long for those pesky SpamBots to find them and pretty soon services such as Gmail started bouncing emails from my webserver thanks to the amount of spam my IP address was generating.

I've been meaning to correct the problem for a while but only got around to doing it this morning. Now I've known about captcha for a while but thanks to one of Jupiter Broadcasting's podcasts, I learnt that a new version of the project hadn't long been released so I was pretty keen to give that a try.

Unfortunately, I couldn't find a simple PHP tutorial to start me off (I did say I was lazy, well time-challenged too), perhaps because it's a very new project or maybe just because I use DuckDuckGo as my search engine. So I rolled up my sleeves, got experimenting and I got it to work without much bother.

Here's how I did it.

Firstly you have to you register your site with the recaptcha project's website. Registration is straightforward and once you done, it describes in two steps what you have to do to get it working on your site, namely:

  1. Client-side integration
  2. Server-side integration

Client-side integration is very straightforward. You have to link to Google's reCaptcha API with an html script tag:

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

As with any external javasrcipt library, this is best placed at the bottom of your document so the rest of the page has a chance to load before making a call outside your website.

Then you have to place the following code inside the HTML form:

   &lt;div class="g-recaptcha" data-sitekey="you_site_key"&gt;&lt;/div&gt;

Place this somewhere appropriate as it's the code that produces the captcha widget.

Server-side integration requires a little more work and it's language dependent so you won't find PHP instructions on the site beyond the basic instructions about calling the API with a GET request using a url with your secret key, the form's generated response code and optionally the remote IP address of the end user who's submitted your form.

Digging further in to the API docs and we learn that the API call responds with simple JSON:

{
  "success": true|false,
  "error-codes": [...]   // optional
}

This is great because most recent versions of PHP can process JSON natively into PHP associative arrays. So all we have to do is make a call to the URL in the correct structure and evaluate the response to see if the end user passed the test of not.

Here's the code required in the simplest form:

//create a variable for the g-recaptcha-response field generated by the API
$response_string = $_POST["g-recaptcha-response"];

//create a variable for your secret key
$secret_key = "your_secret_key";

//create our URL using the correct structure
$capchaAPICcall = "https://www.google.com/recaptcha/api/siteverify?secret=$secret_key&response=$response_string";

//get the response data from google
$data = file_get_contents($capchaAPICcall);

//process the JSON into a PHP array
$result = json_decode($data, true);

//Create an IF statement to test the success
if ($result['success'] != 1)
    {
        //handle the failure here for example:
        header("Location: error.php");
        die();
    } else
        //go on to process your form here
{

So there you have the simplest way to handle the results of a form protected by recaptcha. Point your form at this code and it will query's Google's API to determine if it's a real human being or a spam bot. Naturally you'll want to customise this to suit your own site but it's enough to get you started.

Share on: Diaspora*TwitterFacebookGoogle+Email