How to integrate Google reCAPTCHA in your Website (PHP)

Here i am going to show you how to integrate Google reCAPTCHA in your Sites.

Why Need Google reCAPTCHA :

Google reCAPTCHA is a free service that protects your website from spam and abuse. reCAPTCHA uses an advanced risk analysis engine and adaptive CAPTCHAs to keep automated software from engaging in abusive activities on your site. It does this while letting your valid users pass through with ease.

reCAPTCHA offers more than just spam protection. Every time our CAPTCHAs are solved, that human effort helps digitize text, annotate images, and build machine learning datasets. This in turn helps preserve books, improve maps, and solve hard AI problems.

Register your website and get your Secret Key.

First Login your Google Account and goto following link

Register your Website in following Form. once submit the form google will provide Site key and Secret key.

Here is the Client Side(HTML) code for the Sample form with Text box and submit button.

On submit of this form we will use PHP in back-end to do the Google reCAPTCHA validation.

Client Side Code (HTML)

index.php

<html>
   <head>
      <title>Google recapcha - phpnotebook.com</title>
      <script src='https://www.google.com/recaptcha/api.js'></script>
   </head>
   <body>
      <h1>Google reCAPTHA Demo</h1>
      <form id="comment_form" action="validation.php" method="post">
         <p style="color:blue;">
            <?php if($_GET['msg'] == 'suc'){ echo "Form Posted Successfully"; } else if($_GET['msg'] == 'err'){ echo "The reCAPTCHA was not entered correctly."; } ?>
         </p>
         <br>
         <input type="text" placeholder="Type your Name" required> <br><br>
         <div class="g-recaptcha" data-sitekey="***** Your Google Site Key*******"></div>
         <br>
         <input type="submit" name="submit" value="Submit"> 
      </form>
   </body>
</html>

Server Side Code (PHP)

validation.php

<?php

    $secretkey = "******** Your Secret Key ****************";	 
    $responseKey = $_POST['g-recaptcha-response'];
    $userIP = $_SERVER['REMOTE_ADDR'];
    $url = "https://www.google.com/recaptcha/api/siteverify?secret=$privatekey&response=$responseKey&remoteip=$userIP";
    $response = file_get_contents($url);
    $response = json_decode($response);
    if($response->success){
     header("location:index.php?msg=suc");
    } else {
    header("location:index.php?msg=err");
    }

?>

 

You May Also Like

Leave a Reply

Your email address will not be published. Required fields are marked *