Google reCAPTCHA: Stop Bots using Google reCAPTCHA in PHP

Google reCAPTCHA: Stop Bots using Google reCAPTCHA in PHP

Google reCaptcha is a free service from google that protect our website from spam and abuse.In this post I would like to show how we can integrate google recaptcha into our website. Let start with one by one.

1.) Get recaptcha setup keys from Google:

First of all you need site key and secret key from google console to use recaptcha into your website.To get keys Go to google console and fill all required details and you will get site and secret key.

Create Google Reccaptcha

After done with the fill up of required things, you will get site key and secret key.

Site and Secret key of google recaptcha

2.) Setup of reCAPTCHA with site and secret keys:

Next, You need to configure recaptcha into your website. Create a view file where you will show the captcha to the user.And in this file need to put data site key so that google recaptcha can authenticate with the site key.Here is how code looks.

Recaptcha.php<!DOCTYPE html><html><head><title>Google reCAPTCHA Example</title><script src=’https://www.google.com/recaptcha/api.js’></script></head><body><form method=”post” action=”process.php”><center><legend>Google reCAPTCHA Example</legend><br>First Name :<input type=”text” name=”fname”><br><br>Last Name :<input type=”text” name=”lname”><br><br><div class=”g-recaptcha” data-sitekey=”Your site key”></div><input type=”submit” name=”submit”></center></form></body></html>

3.) Validate reCAPTCHA in server side:

When your users submit the form where you integrated reCAPTCHA, you need to validate that user.

URL:-“https://www.google.com/recaptcha/api/siteverify?secret=”YOUR_SECRET_KEY”&response=”g-recaptcha-response”&remoteip=”UNIQUE_IP_OF_USER’s_SYSTEM”

Through above url you need to send the response to the google and google will verify that user.

Please find below the full code of recaptcha  server side validation.

process.php

<?php
if(isset($_POST['submit'])){

$secret = 'your secret key';
$response = $_POST['g-recaptcha-response'];
if(empty($response)){
echo "<script>alert('Please solve captcha !'); window.location = './recaptcha.php';</script>";
}
$ip = $_SERVER['REMOTE_ADDR'];
$dav = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$response."&remoteip=".$ip);
$res = json_decode($dav,true);
if($res['success']) {
echo "First Name :".$_POST['fname'].'<br>';
echo "Last Name :".$_POST['lname'];
} else {
echo "<script>alert('Please solve captcha !'); window.location = './recaptcha.php';</script>";
}
}
?>

That’s all. Now you can test it.

You may also like this Create captcha using Captcha helper in Codeigniter

Thank you for reading this post. we hope you like this Post, Please feel free to comment below, your suggestion. if you face any issue with this code let us know. We’d love to help!