Skip to content

Using Google reCAPTCHA

Alex Ilea edited this page May 1, 2017 · 2 revisions

Overview

Loris allows users to use Google reCAPTCHA V2 to protect public pages from spam and abuse. Currently this feature is implemented on Request Account page, but can easily be added to other public pages.

Request Account Page Screenshot

Note: A project needs to have reCAPTCHA keys set in Configuration module in order to use this functionality.
Follow set up instruction below to set the keys.


Set up

  1. Login to reCAPTCHA site with your Google account

  2. Follow the steps to register a new site (Note: Loris uses reCAPTCHA V2)

Google reCAPTCHA Screenshot 1

  1. Locate Site Key and Secret Key on reCAPTCHA website

Google reCAPTCHA Screenshot 2

  1. Open Loris Configuration module and copy the Site Key (Public Key) and the Secret Key (Private Key) in the appropriate section as shown in the screenshot.

Loris Configuration Module


Add reCAPTCHA to Loris pages

  1. Display reCAPTCHA on a Loris page

PHP

// Get reCAPTCHA keys
$reCAPTCHAPrivate = $config->getSetting('reCAPTCHAPrivate');
$reCAPTCHAPublic  = $config->getSetting('reCAPTCHAPublic');

// Display reCAPTCHA if both private and public keys are set
if ($reCAPTCHAPrivate && $reCAPTCHAPublic) {
    $tpl_data['captcha_key'] = $reCAPTCHAPublic;
}

Template (Smarty)

{if $captcha_key}
    <div class="g-recaptcha" data-sitekey="{$captcha_key}"></div>
{/if}
  1. Validate request with reCAPTCHA
// Verify reCAPTCHA on POST request
$reCAPTCHAPrivate = $config->getSetting('reCAPTCHAPrivate');
if (isset($_POST['g-recaptcha-response']) && isset($reCAPTCHAPrivate)) {
    $recaptcha = new \ReCaptcha\ReCaptcha($reCAPTCHAPrivate);
    $resp      = $recaptcha->verify(
        $_POST['g-recaptcha-response'],
        $_SERVER['REMOTE_ADDR']
    );
    if (!$resp->isSuccess()) {
        $errors         = $resp->getErrorCodes();
        $err['captcha'] = 'Please complete the reCaptcha!';
    }
}

Additional Resources

To read more about reCAPTCHA, visit https://www.google.com/recaptcha/

Clone this wiki locally