How to Integrate google reCAPTCHA with PHP [ With Example ]

By: Sunil Kumar |  In: PHP  |  Last Updated: 2018/06/25

How to Integrate google reCAPTCHA with PHP [ With Example ]

Spamming is one of the most common problem on the web. Every site owner wants to get rid of spamming whether it is spam traffic or spam messages or spam comments on your site.
To get rid of spamming you need to put some checks on your website. Previously people used to put some random number or string on the screen and verify it on the server-side. But this is the old day’s method. Google’s reCAPTCHA is a new way to verify a user. And it is very simple to verify the user. They just need a single click or tap to prove they are not a robot.
google reCAPTCHA
In this guide, you will learn how to integrate google reCAPTCHA on your website with PHP step by step.

Step 1: Get the reCAPTCHA API key

You need to register your domain and get an API key from google to use reCAPTCHA. Without registering your domain, the captcha widget won’t load on your page.
Register your website at – https://www.google.com/recaptcha/admin
reCAPTCHA-Easy-on-Humans-Hard-on-Bots
Choose the type of captcha you want to use and the domain/domains for you will use this API key and click on the Register Button.

In case you want to implement it on your localhost you need to register your localhost IP address(127.0.0.1) in the settings.

Now you will get your site key and secret key.
reCAPTCHA secret key and site key

Step 2: Adding reCAPTHA to your site

To add reCAPTCHA first you need to include reCAPTCHA JavaScript library in your HTML

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

and add this HTML code where you want to show the reCAPTCHA widget.

<form id="frmContact" action="varify_captcha.php" method="POST" novalidate="novalidate">
   <div class="g-recaptcha" data-sitekey="your_site_key"></div>
   <input type="Submit" name="Submit">
</form>

Replace your_site_key with the actual site key provided by google.
Once you are done refresh your page and you will see the reCAPTCHA widget on your site.

Step 3: Validate the user response

When the user clicks on the captcha widget, a captcha response will be generated which we need to verify at the backend. To verify the reCAPTCHA response we need to add the following PHP code into a PHP file.

<?php
  if(!empty($_POST['g-recaptcha-response']))
  {
        $secret = 'GOOGLE_CAPTACH_SECRET_KEY';
        $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
        $responseData = json_decode($verifyResponse);
        if($responseData->success)
            $message = "g-recaptcha varified successfully";
        else
            $message = "Some error in vrifying g-recaptcha";
       echo $message;
   }
?>

Add your actual secret key in the above code and you are Done.
Here we are capturing the user response and verifying this by making an API call to Google.  If the token is validated successfully, we will receive a success response from the API. That means the captcha is verified and the user can proceed further.
Feel free to write a comment if you face any problem. Will be happy to help you as soon as possible. You can download the demo code from this Github repository as well.

Comments


  • Hi Sunil,
    Very nice to find a full commented exemple. Works perfectly for me. If you have some time you could try the Google V3 Captcha…
    Happy new Year !

  • where does the server side code get placed? in my code? above the header? after the recaptcha widget? just before the recaptcha widget?

    • You can place this code just before the functionality you are implementing. Like if you are using captcha for sign-up form them add the STEP-3 code just before saving the data to the database and save the data only when the captcha got verified.
      Like in the example given, I used it for contact form and contact form only get submitted when google captcha verify API return success.

    • You can place this code just before the functionality you are implementing. Like if you are using captcha for sign-up form them add the STEP-3 code just before saving the data to the database and save the data only when the captcha got verified.
      Like in the example given, I used it for contact form and contact form only get submitted when google captcha verify API return success.

  • Contact form is submitted without captcha, How we will do validate it. It is only showing in front end not working in server side.

    • You can disable/hide the submit button until you verify the captcha token. After the verification enable the submit button.
      In case you need more help, feel free to contact.

    • You can create a PHP file anywhere in the project or paste this code anywhere in your project and post the captcha response to this. Or I can say you can implement this just like you implemented form in HTML and PHP.

  • Ty so much, it worked for me.
    But, how can i put it into every site in my project? And what do i have to do in case there r 2 form in one page?

  • Isn’t the secret key suppose to be secret? If I post that php code in my html page wont the secret key be visible to anyone?

  • WOW, its great article but i get this error “ERROR for site owner: Invalid key type”, even i set key.
    Regards
    SL

  • If you also want to show a message in case a user forgot to check the checkbox, you need to alter the code in step 3.
    Change this:
    if(isset($_POST[‘g-recaptcha-response’]) && !empty($_POST[‘g-recaptcha-response’]))
    To this:
    if(empty($_POST[‘g-recaptcha-response’])){
    $errMsg = ‘Please check the robot checkbox.’;
    } else if(isset($_POST[‘g-recaptcha-response’]) && !empty($_POST[‘g-recaptcha-response’]))

  • You might want to try out hCaptcha.com instead. It seems more accurate than reCAPTCHA for me, and pays the website for the traffic.
    The example above would be identical, except that you change:
    1. “g-recaptcha” to “h-captcha”
    2. “g-recaptcha-response” to “h-captcha-response”
    3. “https://www.google.com/recaptcha/api/siteverify” to “https://www.hcaptcha.com/siteverify”
    .. and that’s it, aside from signing up at hCaptcha.com to get your new sitekey and secret.

  • Hi Sunil,
    Thank you for posting this. The reCAPTCHA appears on my form but even if I don’t check the box it will submit and process the form. I pasted the server side code at the beginning of the verify script right after the <?php. Any suggestions?
    thanks

  • Thank you for this! I got everything working except for the verification part. I too was using if isset, but I was missing the !empty – aren’t these essentially the same thing? Why does it not work with if isset alone? It doesn’t make sense. It was racking my brain for a long time! Thanks again.

  • Hi, I’m having trouble trying to integrate into my PHP form, how do you integrate if current form starts like this:
    if( $_SERVER[‘REQUEST_METHOD’] == ‘POST’ ) {
    if( $_POST[‘form_name’] != ” AND $_POST[‘form_email’] != ” AND $_POST[‘form_subject’] != ” ) {
    $name = $_POST[‘form_name’];
    $email = $_POST[‘form_email’];
    $subject = $_POST[‘form_subject’];
    $phone = $_POST[‘form_phone’];
    $message = $_POST[‘form_message’];
    Thanks for any help…

  • for those who have registered Recaptcha key but don’t have a live server yet or haven’t uploaded their site on a live server, Recaptcha only works on the live server so only for those below are testing keys for testing ReCaptcha on your site. this is only for testing please don’t make a mistake of adding testing keys on a live project or you will be responsible for what might happen
    testing site key = 6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI
    //testing secret key = 6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe

  • Leave a Comment

    Your email address will not be published.

    *


    Sunil Kumar


    I am the owner of acmeextension. I am a passionate writter and reader. I like writting technical stuff and simplifying complex stuff.
    Know More

    Join more than 10,000 others Web Developers