Implementing Google reCAPTCHA using PHP to reduce spam

If you offer a contact form on your website you’re engaged with a never-ending battle with the automated programs that produce spam, also known as spambots. Most likely you have resorted to some kind of CAPTCHA solution, a test to see if the user is human. These tests were often simple math problems or typing out a word from an image, which did reduce spam for a time. Eventually the spam programs caught up and these CAPTCHA tests were not as effective. Google realized this and revamped their own CAPTCHA service, reCAPTCHA.

Even though there are different ways to implement reCAPTCHA, I’m just going to show a somewhat straightforward way to do it using PHP. Before doing anything else, go to the Google reCAPTCHA page and sign up. You can sign up multiple sites. Google will provide you a site key and a secret key for each site. First add the reCAPTCHA Javascript link: <script src='https://www.google.com/recaptcha/api.js'></script> right before the closing </head> tag in the page containing the contact form.

Now the reCAPTCHA widget code needs to be added to the contact form itself. I placed the widget right above the submit button. The widget code consists of a singular <div> element: <div class="g-recaptcha" data-sitekey="<?php echo $siteKey;?>" data-theme="dark" data-size="normal"></div>. If you don’t like the default white background, just set the data-theme attribute to ‘dark’ like in my code example. To save some typing, I assigned my site key and secret key to PHP variables at the top of the page. The last step to complete before writing any code is to download the reCAPTCHA PHP client library from GitHub. The fastest and best way to install the client library is with Composer, a dependency manager for PHP packages.

If you’re looking for ideas on how to setup the code on your own site, a good place to start is the working PHP example found on GitHub. The example is generic enough where it’s easy to add your own custom code. Since my contact form is only a small part of my homepage I added the PHP code consisting of the verification logic at the top of the page. The code first checks if the contact form has been submitted, then if true a check to see if the user’s response to the reCAPTCHA has been verified. If both checks pass, an email is sent to myself with the user’s entered contact form information.

Here’s my PHP code (added before the opening <html> tag):

<?php
// Google reCAPTCHA PHP client library loaded by Composer
require_once __DIR__ . '/vendor/autoload.php';

// declare variables
$siteKey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$errMsg;
$succMsg;
$name;
$email;
$message;

// form submit check
if(isset($_POST['submit'])){


// Google reCAPTCHA response check
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){


// Create an instance of the service using your secret
$recaptcha = new \ReCaptcha\ReCaptcha($secret);
$resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
// retrieve contact form submission data
$name = !empty($_POST['contactName'])?$_POST['contactName']:'';
$email = !empty($_POST['contactEmail'])?$_POST['contactEmail']:'';
$message = !empty($_POST['contactMessage'])?$_POST['contactMessage']:'';
$form_data = array($name, $email, $message);
// check if response is a success


if ($resp->isSuccess()){


// load PHPMailer
require "phpmailer/class.phpmailer.php";
$emailAddress = 'johndoe@test.com'; // email address contact request being sent to
// strip contact form submission data of any special characters
foreach($form_data as $k=>$v)
{


if(ini_get('magic_quotes_gpc'))
$form_data[$k]=stripslashes($form_data[$k]);
$form_data[$k]=htmlspecialchars(strip_tags($form_data[$k]));

}

// encode form data using HTML and send email
$msg=
'<b>Name:</b> '. $name .'<br />
<b>Email:</b> '. $email .'<br />
<b>IP:</b> '.$_SERVER['REMOTE_ADDR'].'<br /><br />
<b>Message:</b><br /><br />
'.nl2br($message).'
';

$mail = new PHPMailer();
$mail->IsMail();
$mail->AddReplyTo($email, $name);
$mail->AddAddress($emailAddress);
$mail->SetFrom($email, $name);
$mail->Subject = "A new message from ". $name ." | contact form feedback";
$mail->MsgHTML($msg);
$mail->Send();

$succMsg = 'Your contact request has submitted successfully.';
$name = '';
$email = '';
$message = '';


}else{


$errMsg = 'Robot verification failed, please try again.';


};


}else{


$errMsg = 'Please click on the reCAPTCHA box.';


};


} else {


$name = '';
$email = '';
$message = '';


};

As you can see the actual code to perform the reCAPTCHA was not that much, which enabled me to include the PHP email function code without cluttering up the page. If you’re planning on doing your own custom solution, it’s a good idea to be aware of all the instances where the PHP code would fail and have a message for the user when it happens. I hope my example helps to demystify implementing Google reCAPTCHA.

Matthew Dailey

Web developer, photographer, and Photoshop user.