Let’s Talk

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. Find a guide to reCAPTCHA v3 here.

Also note you will need to understand basic PHP programming to follow this guide.

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']){
  // Send email
}else{
  // 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.