Google introduced reCaptcha-“Are you a Robot ?” app using PHP


Introduction:

My last article was “Facebook style profile photo upload + Thumbnail Image + Saving into database”.

Bored looking at old Captcha test?

Google introduced latest security update “No CAPTCHA reCAPTCHA API” to protect your website from spam, robots and abuse. It is a complete redesign of Captcha system by Google. They made Captcha system very clear, easy to use. Simple checkbox to confirm they are human or not. Its sound very simple, but it is not, Google does all the magic behind the hood that makes this system more secure and reliable.

Impressive! I have implemented new API class with simple registration form using PHP and HTML. I would like to share with you all step by step.

You can have a look at the demo page, also can download the API class from below.

  Live Demo   Download

Step 1: To get reCAPTCHA Click Here

Step 2: Register your website domain to generate reCAPTCHA secret key as below.

Step 3: Click register to get reCAPTCHA secret key and site key. Store and keep it safe.


i. Use Site key in html code where you want reCAPTCHA should appear.
ii. Google Secret key to communicate with Google API service. Keep it safe place.


Step 4: Create a new page called index.php copy and paste below html code into it.



<!doctype html>
<html lang="en">
  <head>
  <meta charset="UTF-8" />
    <title>Google reCAPTCHA Demo</title>	
	<script src='https://www.google.com/recaptcha/api.js'></script>
	<!-- Latest compiled and minified CSS -->
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
	<link href="http://fonts.googleapis.com/css?family=Open+Sans:400,600,300,700" rel="stylesheet" type="text/css">
	<style type="text/css">
		.formbox { width:400px; height:auto;margin: 0px auto;padding: 20px;border: 1px solid #e5e5e5;box-shadow: rgba(200,200,200,0.7) 0 4px 10px -1px;margin-top:140px;}
	</style>	
  </head>  
  <body>
<?php
include 'lib/ReCaptcha.php';
include 'ActionController.php';
include 'database.php';

$dns = "mysql:host=localhost;dbname=google";
$username = 'root';
$password = '';
$secretKey = '6Lddzf4SAAAAALZFILTYX36qnXvKI3EQk3qDEIia';

$app = new ActionController(new ReCaptcha, new Database($dns,  $username, $password));

$error = "";

if($_SERVER["REQUEST_METHOD"] == "POST")
{
    if (isset($_POST['g-recaptcha-response']) && $_POST['g-recaptcha-response'] !="") {
        $reCaptcha = $_POST['g-recaptcha-response'];

        $app->setGoogleSecretKey($secretKey);
    
        if (!$app->verify($reCaptcha)) {
            $error =  "Please enter your reCAPTCHA again!";
        }  else {
            $app->saveRegistrationInfo($_POST);
        }

    } else {
        $error = "Please check recaptcha before submiting form.";
    }
}
?>

  
  <div class="container" id="content">
  <div class="row formbox">
			<form action="" method="POST" role="form">
			
					<div class="form-group">
						<label class="col-sm-2 control-label">Username </label> 
									<input type="text" name="username" class="form-control" placeholder="Username"/>
					</div>
					
					<div class="form-group">
						<label class="col-sm-2 control-label">Password </label>
									<input type="password" name="password" class="form-control"  placeholder="Password"/>
					</div>
					
					<div class="form-group">
						<label class="col-sm-2 control-label">Phone</label> 
									<input type="text" name="phone" class="form-control" placeholder="Phone"/>
					</div>				
				  <!-- Your reCAPTCHA will appear here-->
				  <div class="g-recaptcha" data-sitekey="6Lddzf4SAAAAAHDKXw0TOcJoG_h-0APraljsIh8W"></div>
				  
				  <span class='msg'><?php echo $error; ?></span>
				  <br>
				  <input type="submit" name="btnSubmit" value="Submit" class="btn btn-sm btn-success">
				  
			</form>
	
	</div>
	
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
</div>

  </body>
</html>


Step 5: Create a PHP file called /lib/ReCaptcha.php paste below code where we will validate reCAPTCHA via Google API and receive response.



class ReCaptcha
{
    public $captchaUrl = "https://www.google.com/recaptcha/api/siteverify";

    public $googleSecretKey;

    public $remoteIp;

    public function setReCaptchaSecretKey($key)
    {
        $this->googleSecretKey = $key;
    }

    public function getGoogleSecretKey()
    {
        return isset($this->googleSecretKey) ? $this->googleSecretKey : null;
    }

    public function validate($reCaptcha)
    {
        $url = null;
        $curlInfo = array();
        $url = $this->captchaUrl."?secret=".$this->getGoogleSecretKey()."&response=".$reCaptcha."&remoteip=".$_SERVER['REMOTE_ADDR'];

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);

        $curlInfo = curl_exec($curl);
        curl_close($curl);

        return $curlInfo;
    }

    public function process($reCaptcha)
    {
        $result =$this->validate($reCaptcha);
        return json_decode($result, true);
    }
}


Step 6: Create a file called ActionController.php via which we will interact with ReCaptcha API. Paste below code into it.



class ActionController
{
    private $connection;

    private $reCaptcha;

    final public function __construct(ReCaptcha $reCaptcha, Database $connection)
    {
        $this->reCaptcha = $reCaptcha;
        $this->connection = $connection;
    }

    public function setGoogleSecretKey($key)
    {
        $this->reCaptcha->setReCaptchaSecretKey($key);
        return true;
    }

    public function verify($reCaptcha)
    {
        $response= array();
        $response = $this->reCaptcha->process($reCaptcha);

        return $response['success'] ? true : false;
    }

    public function saveRegistrationInfo($data)
    {
        // Save information into database
    }
}


Step 7: Create a file database.php paste below code into it. This class act as wrapper class to manipulate database operation.



class Database extends \PDO
{
    public $db;
    
    public function __construct($dns,  $username, $password)
    {
        $this->db = parent::__construct($dns,  $username, $password);
    }
    
    public function getConnection ()
    {
        return isset($this->db) ? $this->db : null;
    }
}



[Note: Make sure curl extension enabled in your php.ini file.]

Using Javascript API for reCAPTCHA:

Another easiest way to integrate reCAPTCHA into your website is using javascript API. You can simply include api.js and div to render reCAPTCHA as below.



<div class="g-recaptcha" data-sitekey="your_site_key"></div>


Explicitly render using javascript onload



<html>
  <head>
    <title>reCAPTCHA demo: Explicit render after an onload callback</title>
    <script type="text/javascript">
      var onloadCallback = function() {
        grecaptcha.render('html_element', {
          'sitekey' : 'your_site_key'
        });
      };
    </script>
  </head>
  <body>
    <form action="" method="POST">
      <div id="html_element"></div>
      <br>
      <input type="submit" value="Submit">
    </form>
    <script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
  </body>
</html>


Minimum Browser Requirement:

Chrome 3.0.195, Firefox 3.0, Internet Explorer 7.0, Opera 10.10, Safari 4.0

Conclusion:

Hope you found this article helpful. Don't forget to like, share with friends, or leave your comments below.

Keep visiting for latest posts. Have a nice day.

Follow Us On Facebook Open Source Web Developers by Appsntech facebook group Twitter Open Source Web Developers by Appsntech twitter group Google+ Open Source Web Developers by Appsntech Google group Linkedin Open Source Web Developers by Appsntech, LinkedIn group
Copyright @2011-2015 appsntech.com. All rights reserved. Powered By- Sanjoy Dey Productions