Integrating Googles new reCAPTCHA in PHP

For the past several years Google’s reCAPTCHA has helped verify that a user is not a bot by forcing you to decipher warped text. reCAPTCHA’s method of protecting websites from spam has always been a kind of burden on the end user who has to solve the captcha to prove that he is human and not a bot.

new_recaptcha

Google recently released a new captcha API called “No CAPTCHA” reCAPTCHA, which utilizes an Advanced Risk Analysis engine that is capable of discerning between users and bots. So instead of solving a jumbled box of text all a user has to do is check a box. However, if the risk analysis engine can’t surely identify whether a user is a human or a robot than it will provide you with the regular captcha box.

View Demo

Getting started

To get started head over to Google reCaptcha. You need to sign up for an API key pair for your site which consists of a site key and secret key. The site key is used to display the widget on your site while the secret key authenticates communication between your applications backend and the reCAPTCHA API server to verify the user’s response. The secret key needs to be kept safe for security purposes.

Rendering the reCaptcha widget

The easiest method for rendering the reCAPTCHA widget on your page is to include the necessary JavaScript resource and a g-recaptcha tag. The g-recaptcha tag is a DIV element with class name ‘g-recaptcha’. You also need to put your site key in the data-sitekey attribute. The following code shows the integration in our demo page.

<!DOCTYPE HTML>
<html>
<head>
<title>Google new reCaptcha</title>
<meta charset="UTF-8" />
<link type='text/css' rel='stylesheet' href='css/reset.css' />
<link type='text/css' rel='stylesheet' href='css/structure.css' />
<script src="https://www.google.com/recaptcha/api.js"></script>
</head>
<body>
<form class="box login" method="post" action="">
<fieldset class="boxBody">
  <label id="msg"><?php echo $message; ?></label>
  <label>Username</label>
  <input type="text" tabindex="1" name="username" value="demo" required>
  <label>
  <a href="#" class="rLink" tabindex="5">Forget your password?</a>Password
  </label>
  <input type="password" name="password" tabindex="2" value="demo" required>
</fieldset>
<div class="g-recaptcha" data-sitekey="YOUR SITE KEY"></div>
<footer>
  <input type="submit" class="btnLogin" value="Login" tabindex="4">
</footer>
</form>
<footer id="main">
</footer>
</body>
</html>

So basically you will need to add only 2 lines to the page where you need to display the reCaptcha. One is the javascript resource.

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

And the other is the html code where the widget will be displayed.

<div class="g-recaptcha" data-sitekey="YOUR SITE KEY"></div>

Note: The reCaptcha javascript resource must be loaded using the HTTPS protocol and can be included from any point on the page without restriction.

Validating the user’s response

When a reCAPTCHA is solved by end user, a new field g-recaptcha-response will be populated in HTML. You can verify the user’s response by checking the
g-recaptcha-response POST parameter in the backend when the user submits the form on your site. You will then need to pass the response along with the secret key an ip address (currently optional) to the Google API. The format of which is the following.

https://www.google.com/recaptcha/api/siteverify?secret=your_secret&
response=response_string&remoteip=user_ip_address

The API will return a JSON response object with the following format.

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

The following PHP code shows how we can pass the g-recaptcha-response and reCaptcha response string to the API for verification.

<?php
 
class GoogleRecaptcha 
{
    /* Google recaptcha API url */
    private $google_url = "https://www.google.com/recaptcha/api/siteverify";
    private $secret = 'YOUR_SECRET_KEY';
 
    public function VerifyCaptcha($response)
    {
        $url = $this->google_url."?secret=".$this->secret.
               "&response=".$response;
 
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curl, CURLOPT_TIMEOUT, 15);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, TRUE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, TRUE); 
        $curlData = curl_exec($curl);
 
        curl_close($curl);
 
        $res = json_decode($curlData, TRUE);
        if($res['success'] == 'true') 
            return TRUE;
        else
            return FALSE;
    }
 
}
 
$message = 'Google reCaptcha';
 
if($_SERVER["REQUEST_METHOD"] == "POST")
{
    $response = $_POST['g-recaptcha-response'];
 
    if(!empty($response))
    {
          $cap = new GoogleRecaptcha();
          $verified = $cap->VerifyCaptcha($response);
 
          if($verified) {
            $message = "Captcha Success!";
          } else {
            $message = "Please reenter captcha";
          }
    }
}
 
 
?>

The VerifyCaptcha() class method will return a boolean value on the success of the verification.

Customizing the widget

The widget currently supports 2 themes – dark, light. The default is light. To change to a dark theme add the data-theme attribute.

<div class="g-recaptcha" data-theme="dark" data-sitekey="SITE_KEY"></div>

The javascript resource autodetects the users language to display the widget, however you can force a certain language using the hl parameter. The list of language codes can be found here.

<script src="https://www.google.com/recaptcha/api.js?hl=fr"></script>
Download Code file
Downloads : 2090 / File size : 4.2 kB


6 thoughts on “Integrating Googles new reCAPTCHA in PHP

  1. You could use:
    .
    $url = $this->google_url.”?secret=”.$this->secret.”&response=”.$response;
    $data = file_get_contents($url);
    $res = json_decode($data, TRUE);
    .

  2. Hi,

    I try to add the php code to my existing file to make reCAPTCHA required but is not working for me.

    Can any one help.

    below is my code of contac.php form.

    Thanks in advance
    Sou

    <?php

    $EmailFrom = $_REQUEST['email'];
    $EmailTo = "email@example.com";
    $Subject = "New Message";
    $Name = Trim(stripslashes($_POST['name']));
    $Email = Trim(stripslashes($_POST['email']));
    $Subject = Trim(stripslashes($_POST['subject']));
    $Tel = Trim(stripslashes($_POST['tel']));
    $Message = Trim(stripslashes($_POST['message']));

    // validation
    $validationOK=true;
    if (!$validationOK) {
    echo "Error";
    exit;
    }

    // prepare email body text
    $Body = "";
    $Body .= "Name: ";
    $Body .= $Name;
    $Body .= "\n";
    $Body .= "Email: ";
    $Body .= $Email;
    $Body .= "\n";
    $Body .= "Subject: ";
    $Body .= $Subject;
    $Body .= "\n";
    $Body .= "Contact Number: ";
    $Body .= $Tel;
    $Body .= "\n";
    $Body .= "Message: ";
    $Body .= "\n";
    $Body .= $Message;
    $Body .= "\n";
    $Body .= "\n";

    // send email
    $success = mail($EmailTo, $Subject, $Body, "From: “);

    // redirect to success page
    if ($success){
    echo “Succes”;
    }
    else{
    echo “Error”;
    }

    class GoogleRecaptcha
    {
    /* Google recaptcha API url */
    private $google_url = “https://www.google.com/recaptcha/api/siteverify”;
    private $secret = ‘YOUR_SECRET_KEY';

    public function VerifyCaptcha($response)
    {
    $url = $this->google_url.”?secret=”.$this->secret.
    “&response=”.$response;

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($curl, CURLOPT_TIMEOUT, 15);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    $curlData = curl_exec($curl);

    curl_close($curl);

    $res = json_decode($curlData, TRUE);
    if($res[‘success’] == ‘true’)
    return TRUE;
    else
    return FALSE;
    }

    }

    $message = ‘Google reCaptcha';

    if($_SERVER[“REQUEST_METHOD”] == “POST”)
    {
    $response = $_POST[‘g-recaptcha-response’];

    if(!empty($response))
    {
    $cap = new GoogleRecaptcha();
    $verified = $cap->VerifyCaptcha($response);

    if($verified) {
    $message = “Captcha Success!”;
    } else {
    $message = “Please reenter captcha”;
    }
    }
    }

    ?>

  3. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

    REALLY unsecure!

Comments are closed.