reCaptcha, a quick integration guide (PHP)

reCaptcha, a quick integration guide (PHP)

June 18th, 2015 // 7:35 pm @

I didn’t have a need to make an online application, but recently, I was woring on an HTTP app, and really needed to keep the annoying spammers out. So I tried to give Google’s reCaptcha a chance, and I should say, it’s fantastic!

So, I am going to write a really quick tutorial on how to integrate reCapthca with your applications. I am using PHP for this application

Setup your reCaptcha account

Login to https://www.google.com/recaptcha and create a reCaptcha account. take a note of the following:

  • Site key – AlphaNumeric value
  • Secret key – AlphaNumeric value
  • Two part code Snipet
    •  The <head> code
      • <script src='https://www.google.com/recaptcha/api.js'></script>
    • The HTML code, goes at the end of the form, before </form>
      • <div class="g-recaptcha" data-sitekey="YOUR_SIT_KEY_GOES_HERE"></div>

Integrate to our form

Now that we have all the info, let’s create a simple form and test our code. Create one file, index.php and enter all of these into that file

HEAD

<html>
 <head>
 <title>reCaptcha Integration Test</title>
 <script src='https://www.google.com/recaptcha/api.js'></script>
 </head>
 <body>
 <h1>Google reCAPTHA TEST</h1>
 <form action="#" method="post">
 <input type="text" placeholder="Your name" size="40"><br>
 <input type="email" placeholder="Your email" size="40"><br>
 <textarea name="comment" rows="10" cols="60"></textarea><br>
 <input type="submit" name="submit" value="SUBMIT"><br><br>
 <div class="g-recaptcha" data-sitekey="YOUR_SIT_KEY_GOES_HERE"></div>
 </form>
 </body>
</html>

 

 

BODY/PHP


<?php
if($_POST[name]){
if(isset($_POST['g-recaptcha-response'])){
 $captcha=$_POST['g-recaptcha-response'];
 }
 if(!$_POST['g-recaptcha-response']){
 echo '<h2>You did not check Captcha</h2>';
 exit;
 }
 $secretKey = "SECRET_KEY_GOES_HERE";
 $ip = $_SERVER['REMOTE_ADDR'];
 $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
 $responseKeys = json_decode($response,true);
 if(intval($responseKeys["success"]) != 1) {
 echo '<h4>Spam Detected</h4>';
 } else {
 echo '<h4>You are all good to go!</h4>';
 }
 }
?>

 

 

 


Category : Articles &Common Techniques &Tricks

Comments are closed.

On LinkedIn

LinkedIn

.

"I have no special talent.
I am only passionately
curious.
"
Albert Einstein

Subscribe Now