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=’’></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.


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.



$secret = 'your secret key';
$response = $_POST['g-recaptcha-response'];
echo "<script>alert('Please solve captcha !'); window.location = './recaptcha.php';</script>";
$dav = file_get_contents("".$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!