17 July 2020: Updated the class provided in this article to make it easier to use.
For those of you using Google reCAPTCHA to weed out spam on your websites, here’s a code snippet for verifying the reCAPTCHA v2 tickbox response on the server-side using PHP.
GoogleRecaptchaV2.php
<?php
class GoogleRecaptchaV2 {
const VERIFY_URL = 'https://www.google.com/recaptcha/api/siteverify?secret=%s&response=%s&remoteip=%s';
// Creates and submits the cURL. Returns the data.
private static function curl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$data = curl_exec($ch); curl_close($ch); return $data;
}
// Sends the reCaptcha URL. You can optionally provide the $g_response object, which is normally gotten from $_POST['g-recaptcha-response'].
public static function process($secret, $g_response = null) {
// For Cloudflare users. Remove if not needed.
if(isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
$_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
}
// Automatically find the POST response if it is not provided as an argument.
if(!$g_response) $g_response = $_POST['g-recaptcha-response'];
// Generates the URL to query.
$url = sprintf(self::VERIFY_URL,$secret,$g_response,$_SERVER['REMOTE_ADDR']);
// cURLs the URL and returns the response.
$verify_response = json_decode(self::curl($url), true);
if (empty($verify_response['success'])) return false;
return true;
}
}
Here’s how to use it:
GoogleRecaptchaV2::process( YOUR_SECRET_KEY );
The PHP code works with the following HTML elements inside your <form> tag (if you need more information, read the Google docs here):
<div class="g-recaptcha" data-sitekey="YOUR_RECAPTCHA_SITE_KEY"></div> <script src="https://www.google.com/recaptcha/api.js" defer></script>
Remember to replace YOUR_RECAPTCHA_SITE_KEY with your own reCAPTCHA site key. If you need a pair of reCAPTCHA site and secret keys, head to google.com/recaptcha to generate a new set.
Styling the reCAPTCHA v2 tickbox
If you don’t like the default reCAPTCHA style, you can add a data-theme="dark" attribute to the reCAPTCHA HTML element. Yes, this makes it come in black.
<div class="g-recaptcha" data-sitekey="YOUR_RECAPTCHA_SITE_KEY" data-theme="dark"></div>
You can also centre or right-align your reCAPTCHA box with the following CSS.
/* Centre-align */
.g-recaptcha > div { margin:0 auto;display:block; }
/* Right-align */
.g-recaptcha > div { margin:0 0 0 auto;display:block; }
Happy v2 reCAPTCHA-ing folks.
