Skip to content

Google reCaptcha Example

Victor Jonsson edited this page Apr 20, 2017 · 3 revisions

Example use of Google reCaptcha

Just a quickie wiki showing usage of the Google reCaptcha feature.

Register for a key from Google

You'll need to register to obtain a site key and shared key pair to use on your site.

https://www.google.com/recaptcha/intro/index.html

The Resources | Guide section shows API usage and has examples for various server-side implementations, including the PHP module referenced here.

Usage

You can use either the HTML data-validation- tags or the JavaScript config settings. JavaScript config settings will overwrite HTML values if both are used.

HTML:

<form id="myForm">
    <input type="text" id="name" name="name" placeholder="Name..."
        data-validation="required">
    <input type="hidden" data-validation="recaptcha" 
        data-validation-recaptcha-sitekey="..." 
        data-validation-recaptcha-size="compact" 
        data-validation-recaptcha-theme="dark">
    <button type="submit">Submit</button>
</form>

JS:

$(function(){
    'use strict';
    $('#myForm').validate({
        modules: 'security',
        reCaptchaSitekey: '...',
        reCaptchaSize: 'normal',
        reCaptchaTheme: 'light',
        onSuccess: function() {
            /* 
                put your AJAX code here 
            */
            return false;  // to prevent default submit action
        },
    });
});

PHP:

<?php 
    require 'ReCaptcha/autoload.php';  // get this from Google

	function addError ($errstr) {
		/* your code to handle errors */
	}

	// check reCAPTCHA
	if (isset($_POST['g-recaptcha-response'])) {
		$recaptcha = new \ReCaptcha\ReCaptcha('...');  // your shared key from Google
		$resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
		if (!$resp->isSuccess()) {
			// error:  grecaptcha failed verification
			foreach ($resp->getErrorCodes() as $code) {
				addError ($code);
			};
		};
	} else {
		// error:  grecaptcha not found
		addError ( 'g-recaptcha-response not found' );
	}