Tuesday, 4 August 2015

Google reCAPTCHA with PHP tutorial

Login to your Google account and submit the form.
capcha1
Once submit, Google will provide you following two information.
  • Site key
  • Secret key


Integrate it into your website.

To integrate it into your website you need to put it in client side as well as in Server side. In client HTML page you need to integrate this line before <HEAD> tag.

<script src='https://www.google.com/recaptcha/api.js'></script>
And to show the widget into your form you need to put this below contact form, comment form etc.

<div class="g-recaptcha" data-sitekey="== Your site Key =="></div>
When the form get submit to Server, this script will send ‘g-recaptcha-response’ as a POST data. You need to verify it in order to see whether user has checked the Captcha or not.

Simple comment form with Google reCAPTCH:

Index.html
<html>
  <head>
    <title>Google recapcha demo - Codeforgeek</title>
    <script src='https://www.google.com/recaptcha/api.js'></script>
  </head>
  <body>
    <h1>Google reCAPTHA Demo</h1>
    <form id="comment_form" action="form.php" method="post">
      <input type="email" placeholder="Type your email" size="40"><br><br>
      <textarea name="comment" rows="8" cols="39"></textarea><br><br>
      <input type="submit" name="submit" value="Post comment"><br><br>
      <div class="g-recaptcha" data-sitekey="=== Your site key ==="></div>
    </form>
  </body>
</html>
This will generate this form.
Screenshot from 2014-12-05 10:36:46
On server side i am using PHP for now. So on Form submit request we will check the POST variable.
form.php
<?php

        $email;$comment;$captcha;
        if(isset($_POST['email'])){
          $email=$_POST['email'];
        }if(isset($_POST['comment'])){
          $email=$_POST['comment'];
        }if(isset($_POST['g-recaptcha-response'])){
          $captcha=$_POST['g-recaptcha-response'];
        }
        if(!$captcha){
          echo '<h2>Please check the the captcha form.</h2>';
          exit;
        }
        $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=YOUR SECRET KEY&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
        if($response.success==false)
        {
          echo '<h2>You are spammer ! Get the @$%K out</h2>';
        }else
        {
          echo '<h2>Thanks for posting comment.</h2>';
        }
?>

Software Developer in php (3 - 5 years , 2.00 - 12.00 Lacs) interview question Neosoft Technologies

Laravel 5 Eloquent Explained in the Simplest Way Facades in Laravel. Why and How? How to Register & Use Laravel Service Providers ...