How to Integrate Google reCAPTCHA with PHP [Full Guide]

Spamming is a very common issue for all websites. Every web developer faces to the spamming problem and implements captcha verification.

Google Recaptcha is one of the best options to get free from spam.

In this tutorial, we are going to see how to use Recaptcha in PHP or How to use Google reCaptcha code in PHP.

Step 1. Register Your Site and Get API Key (Site Key and Secret key)

First, you need to register your website at Google reCaptcha admin console and get the site key and secret key.

Label: name of your site 

reCatpcha type: Choose reCaptcha v2 >> Choose I’m not a robot Checkbox.

Domains: Mention the domain name of your website.

Register site to Google reCaptcha

Once submitted Google will provide you following two things

  1. Site Key
  2. Secret Key

Copy the Google reCaptcha site key and secret key for later use in the reCaptcha integration code.

.

Step 2.  HTML [Adding Google reCaptcha to Form]

First, include the reCAPTCHA JavaScript API library. Paste this snippet before the closing head tag on your HTML template:

<script src='https://www.google.com/recaptcha/api.js' async defer > 

Paste this snippet at the end of the <form> where you want the reCAPTCHA widget to appear and replace the below date-sitekey value with your own Site key.

<div class="g-recaptcha" data-sitekey="your_site_key"> 

For more details, you can see given below example 

Example :

<form method="POST">
   <input type="text" name="name" value="" /><br>
   <input type="text" name="email" value="" /><br>
   <textarea name="message"></textarea><br>
 
  <div class="g-recaptcha" data-sitekey="your_site_key"></div><br>
 
  <input type="submit" name="submit" value="SUBMIT">
</form>

Once you have done, refresh your web page and you will see reCaptcha widget added in form.

Step 3. PHP Code [Validate reCAPTCHA]

Replace the secret key with your own.

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

if (isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])) { 
 
    $secretKey   = "your_site_key";
    $responseKey = $_POST['g-recaptcha-response'];
    $userIP      = $_SERVER['REMOTE_ADDR'];
    $url         = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey&remoteip=$userIP";
    $response    = file_get_contents($url);
    $response    = json_decode($response);
 
    if($response->success){
        echo "Verification success.";
    } else {
        echo "Verification failed";
    }

}
} ?> 

Once you have changed Secret Key with your own, you are done. 

If you have any query related to Google reCaptcha integration, feel free to comment.

Leave a Comment