How to add Google reCAPTCHA to a Form (PHP/HTML)

When you need to add a relatively simple new feature like this, if you’re anything like me, you don’t want to be reading through pages and pages of documentation; you want an example you can implement quickly then edit as you see fit. I couldn’t find any such thing when I was integrating, so hopefully these 4 simple steps will help you.

Please note, this guide relates to reCAPTCHA V2.

Step 1

Sign up and get your keys here: https://www.google.com/recaptcha/admin (you will get a SITE key and a SECRET key, used later)

Step 2

Include this on your page:

<script src="https://www.google.com/recaptcha/api.js"></script>

Step 3

Add the following into your form:

<div class="g-recaptcha brochure__form__captcha" data-sitekey="YOUR SITE KEY"></div>

Step 4

On form submission do this:

$recaptcha = $_POST['g-recaptcha-response'];
$res = reCaptcha($recaptcha);
if(!$res['success']){
  // Error
}

Using the following function:

function reCaptcha($recaptcha){
  $secret = "YOUR SECRET KEY";
  $ip = $_SERVER['REMOTE_ADDR'];

  $postvars = array("secret"=>$secret, "response"=>$recaptcha, "remoteip"=>$ip);
  $url = "https://www.google.com/recaptcha/api/siteverify";
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_TIMEOUT, 10);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
  $data = curl_exec($ch);
  curl_close($ch);

  return json_decode($data, true);
}

This code is free to use at your own discretion. It comes without warranty. Please feel free to feedback any edits.


We'd love to hear from you!

If you think Bronco has the skills to take your business forward then what are you waiting for?

Get in Touch Today!

Discussion

Write a comment...
  • David Fletcher

    I am very interested in this
    I have the steps 1, 2 and 3 inplace and the captcha form is displayed, and captcha can be checked.
    Now, what do I do with step 4. There are two pieces of code and I dont know where to place them.
    Thanks in advance

    • Chris Antcliff

      Sorry for the late reply but hopefully this will be useful.

      Step 4 is done after form submission; this is where you would normally send the email if you’re doing a contact form, or allow the user to set up an account or whatever feature you’re trying to stop bots from accessing.
      The function can go anywhere on the page or included from a functions file – anywhere as long as it’s accessible to the page you’re working on.

  • Derek

    Sorry for the rookie question but what am I looking for when filling in three remote address in line three of the last step. “$ip = $_SERVER[‘REMOTE_ADDR’]”

    • Chris Antcliff

      Hi, you don’t need to change that line – it gets the user’s IP address.

  • Peter

    Hi, Just wanted to say you really simplified it. Really great post

    • Chris Antcliff

      Thanks Peter, glad it helped.

  • Sami

    Yes good i like it

  • Martin

    Nice and easy to follow. I’ve used reCAPTCHA v2 for simplicity. However, form submission continues successfully whether you click the checkbox or not. Is this correct? If not… what have I done wrong?

  • Kay

    Works like a Charm.Great Work Chris. Had a error free experience implementing this.

    However, you would like to apprise visitors that this works for reCaptcha V2. For V3 it gives error of Invalid Key Type. I changed to V2 and it worked.

    Great reading,nice code .

    Thanks.

    • Chris Antcliff

      Thanks for the feedback Kay, and I’m glad it helped you. I have added a note in the article regarding V2.

  • robert

    I don’t understand step 4 Must this be copy past in the process form.php?

    • Chris Antcliff

      Yes – it needs to be integrated with your website’s code.

      $res['success'] means the reCAPTCHA has been completed successfully. After that it’s up to you to do whatever you need to i.e. send an email or whatever you’re trying to protect from bots.

  • ida

    Hi there. A bit of a rookie here. I’ve completed the steps however on submission i get this error “Unable to send your message. Please fix errors then try again.”

    I think this is a result of pasting my step 4 codes. Do I put the two once after another? other than the secret key, is there anything else I need to change? Thank you for your help.

    • Chris Antcliff

      Hi. You can put the function (the second bit of step 4) anywhere in your PHP file. The first part you need to intergrate with the logic of your form, so any error messages need to be output within the !$res['success'] IF statement. You will probably want an ELSE after that to deal with sending the message itself.

      The error message you’re getting doesn’t look like anything to do with reCAPTHA, more to do with your website – it looks like, for whatever reason, the message isn’t getting sent; perhaps due to you not integrating your current website code with the reCAPTCHA bit of code.

  • Gail Kearney

    Hi Chris, thanks for posting this helpful code. I am rusty, where exactly on my mail_form.php page do I paste the 2 bits of code in Step 4? Every place I try, it pastes in all white, not color coded like working code.

    The reCAPTCHA is showing correctly on my Contact page, but I can submit without checking the “I am not a robot” box.

    • Chris Antcliff

      Hi Gail,

      It sounds like you’re not placing it within PHP tags in your file; try adding at the end. The code needs to run after the form has been submitted and you need to check $res['success'] before continuing whatever your site does on form submission.

  • Peter

    Thanks for this, just having trouble figuring out where I put form submision PHP

    $recaptcha = $_POST[‘g-recaptcha-response’];
    $res = reCaptcha($recaptcha);
    if(!$res[‘success’]){
    // Error
    }

    Does it go here like this:

    • Chris Antcliff

      Hi Peter,

      It essentially just goes wherever the code of your current form submission is; before whatever your page does now on submission (e.g. send an email), you need this code which checks the captcha has been successful or not.

  • Ryan McGurk

    this worked correctly and easily. thank you

    • Chris Antcliff

      Cheers Ryan, glad it helped.

  • Sapir

    thank you so much!

    • Chris Antcliff

      You’re welcome.

  • Chiranth

    Hey, I am a bit of a rookie, I have added both the parts of the Step-4 inside the form.php which is executed after filling the form and hitting submit. But even without finishing the reCaptcha the form is being executed.

    • Chris Antcliff

      Hi,
      Have you intercepted what your code was doing to submit the form before? You should only complete the submission if $res['success']

  • Theo Voorbij

    Hello, like others here, I don’t get part 4. I did HTML 3 and 4 a very long time ago. I bought a template I liked and went from there. I am able to change everything to my liking, no problems there. Only problem I’m facing is a lot of spam everyday again from my contact form. That’s why I was looking for ReCaptcha 2. I have my keys for both 2 and 3.

    I added step 2 and 3 to my contacts page form. There’s also a mail.php with codes to check if an e-mail address is correct and other code. It also addresses the correct mail it should been send to. I experimented a bit but don’t get it to work.
    I assume the step 4 code should go into the mail.php? If so could it be it’s conflicting with original code? Thanks for your time.

    • Chris Antcliff

      Hi Theo,

      Within mail.php, where it sends the email, you need to check $res['success']. If valid, then send the email.

      You also need to put the reCaptcha() function somewhere – maybe you have a functions.php file.

  • Manish

    thanks for these codes, they are working nicely.

    • Chris Antcliff

      You’re welcome, glad it helped.

  • Richard

    I’ve worked in IT and web development for years, but I’ve never had to use a captcha. I needed to implement one on a web form this morning. I did a quick google search for “add captcha to html form”, and this page was the second result. I followed your instructions, it took me 10 minutes from start to finish, and it works perfectly. Thank you! 🙂

    • Chris Antcliff

      Thanks for the comment, glad it helped!

  • SE

    Thanks for sharing the HTML code – I wish I found this option for my contact form sooner!

    • Chris Antcliff

      You’re welcome.

  • Louise

    Dude – you are a life saver. Worked a charm with version 2 reCAPTCHA. I wish Google had been so clear with their instructions. You should be sending them a bill.

    • Chris Antcliff

      Haha thanks, glad it helped.

  • Todd

    Doesn’t work, can still submit my form without checking the box, upon checking the other comments on here it is clear that my confusion around this is mirrored by other people, being referred to other documentation is just no good. Step 4 is just as confusing in terms of where you put it: do you put it on the PHP document? Do you put it in the HTML document? Do you put it in the HTML document underneath the form? Do you put it in the HTML document inside the form? Do you put the two scripts together? Do you separate the two scripts in separate script tags? Do you put both scripts into the HTML document? Do you put both scripts in the PHP document? Do you put one in the PHP document and the other in the HTML document? Or do you really push the boat out and put them in the “Thank you” page? Do you put in on the fridge? Do you put it in the garden? Or maybe, if I put them in my garden shed, that might work.

    Also, the OP really should not be encouraging users to have the script containing the secret key in the HTML document, as this can be obtained with just a right mouse button click and selecting the “Inspect element” option.

    When I to put this into a separate script document, I just get the parsing error. I’m sorry but either write a clear, concise set of instructions or don’t, because you’re just making peoples lives harder. Have the sample syntaxes in their respective documents in situ.

    • Chris Antcliff

      You can’t help all the people all the time.

      I’m sorry a free guide is “just no good” for you but as you will also have seen from the comments it’s helped a lot of people. While it’s a simple process spelled out step by step it still requires a modicum of technical knowledge to achieve and to the commenters you highlighted I’ve tried to help as much as possible.

      (You can’t see PHP by looking at HTML source code btw).

      All the best for getting it working. If you need a hand feel free to get in touch.

  • Raine

    Hi, I did all the steps you have mentioned, but where the captcha is supposed to appear it says “ERROR for site owner: Invalid key type” eventhough I triple checked the key, and it is correct.

    Any help is appreciated

    • Chris Antcliff

      Hi Raine,

      It looks like you’re getting keys for a different version of reCAPTCHA; this guide is specifically for version 2.

  • Leida

    Hello,

    I made a form using your recaptcha, but when I hit submit the form is just sent. The recapcha is not working. I put it below the code.

    $secret, “response”=>$recaptcha, “remoteip”=>$ip);
    $url = “https://www.google.com/recaptcha/api/siteverify”;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
    $data = curl_exec($ch);
    curl_close($ch);

    return json_decode($data, true);
    }
    ?>

    Of course with the secret key. What am I doing wrong. I put the first sentence just above the closing body tag.
    The second above the button that should submit the form. I’ve been at it for days and nothing helps.

    Sincerely, Leida

    • Chris Antcliff

      Hi Leida,

      Are you using the first part of Step 4? It sounds like you’re letting the form submit without checking the result.

      Chris

  • Sandeep

    Thanks it worked

    • Chris Antcliff

      Glad it helped! You’re welcome.

Add a Comment