New Google reCAPTCHA integration with PHP


In this tutorial, I will show you easiest way to integrate google reCAPTCHA version 2 in your PHP project. The reCAPTCHA help to protect your site from bot attacks and spams. It will ensure that only human can use your site. Google has released their new version of reCAPTCHA which is more secure than the older version. The new version is easy to use for visitors too as they don't want to type some characters into a text box Instead, choose some appropriate images. 

Here is the sample output of new google reCAPTCHA.

 Google reCAPTCHA  demo 

Now before we start coding we need to register our site and get a client key and secret key from google. You can register your site for free from https://www.google.com/recaptcha/admin. The registration process is fairly simple and straight forward so I am skipping it.

Now, lets start coding. Inside your config.php file

<?php
return [
	'client-key' => 'your client key',
	'secret-key' => 'your secret key'
];

Codes for login.php file (View Page)

<?php
$config = require('config.php');
?>
<html>
  <head>
    <title>reCAPTCHA demo</title>
    <script type="text/javascript">
      var onloadCallback = function() {
        grecaptcha.render('html_element', {
          'sitekey' : '<?php echo $config['client-key']; ?>'
        });
      };
    </script>
  </head>
  <body>
    <form action="admin.php" 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>

Codes for admin.php file (form action)

<?php
require 'Recaptcha.php';

$recaptcha = $_POST['g-recaptcha-response'];

$object = new Recaptcha();
$response = $object->verifyResponse($recaptcha);

if(isset($response['success']) and $response['success'] != true) {
	echo "An Error Occured and Error code is :".$response['error-codes'];
}else {
	echo "Correct Recaptcha";
}

Now the main reCAPTCHA PHP library created by me. 

<?php

class Recaptcha{
	
	public function __construct(){
        $this->config = require('config.php');
    }

	public function verifyResponse($recaptcha){
		
		$remoteIp = $this->getIPAddress();

		// Discard empty solution submissions
		if (empty($recaptcha)) {
			return array(
				'success' => false,
				'error-codes' => 'missing-input',
			);
		}

		$getResponse = $this->getHTTP(
			array(
				'secret' => $this->config['secret-key'],
				'remoteip' => $remoteIp,
				'response' => $recaptcha,
			)
		);

		// get reCAPTCHA server response
		$responses = json_decode($getResponse, true);

		if (isset($responses['success']) and $responses['success'] == true) {
			$status = true;
		} else {
			$status = false;
			$error = (isset($responses['error-codes'])) ? $responses['error-codes']
				: 'invalid-input-response';
		}

		return array(
			'success' => $status,
			'error-codes' => (isset($error)) ? $error : null,
		);
	}


	private function getIPAddress(){
		if (!empty($_SERVER['HTTP_CLIENT_IP'])) 
		{
		$ip = $_SERVER['HTTP_CLIENT_IP'];
		} 
		elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) 
		{
		 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
		} 
		else 
		{
		  $ip = $_SERVER['REMOTE_ADDR'];
		}
		
		return $ip;
	}

	private function getHTTP($data){
		
		$url = 'https://www.google.com/recaptcha/api/siteverify?'.http_build_query($data);
		$response = file_get_contents($url);

		return $response;
	}
}

The above view and form action pages are extremely simplified one. You need to modify it according to your login requirements. You can also download above codes from my GitHub. The download link is given below

https://github.com/geordyjames/google-reCAPTCHA-Version-2-PHP-Library


Web development
22nd Jul 2018 01:55:49 AM
PHP CodeIgniter Laravel
5913

ShareurCodes

ShareurCodes is a code sharing site for programmers to learn, share their knowledge with younger generation.