I’m not a fan of CAPTCHAs as I think you should use less instrusive methods where possible. However, I had to add Google’s reCAPTCHA. It's easy to do. you will just need to create your keys first.
Add this to your page:
<script src="https://www.google.com/recaptcha/api.js"></script>
Then add this to your form:
<div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY"></div>
This will submit a POST var called g-recaptcha-response
. You need to validate this with Google’s server. You can either use cURL or file_get_contents()
. Although cURL is more verbose it is more powerful. With file_get_contents()
you need to be able to change allow_url_fopen
which is unlikely to be an issue — but with cURL it generally works out-of-the-box and is better for handling errors.
Your validation will look something like this:
$data = [
'secret' => 'YOUR_SECRET_KEY',
'response' => @$_POST['g-recaptcha-response']
];
$curl = curl_init();
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
$response = curl_exec($curl);
$response = json_decode($response, true);
if ($response['success'] === false) {
// Failure
} else {
// Success
}
Tim Bennett is a web designer and developer. He has a First Class Honours degree in Computing from
Leeds Metropolitan University and currently runs his own one-man web design company, Texelate.