New Google reCAPTCHA integration with PHP

New Google reCAPTCHA integration with PHP

In this post we will show you New Google reCAPTCHA integration with PHP, hear for New Google reCAPTCHA integration with PHP we will give you demo and example for implement.

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
Hope this code and post will helped you for implement New Google reCAPTCHA integration with PHP. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve onlincode. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs us

Comments