How to Add BotDetect PHP CAPTCHA Protection to Laravel 5.0 Applications (BotDetect v3.0; deprecated)

Adding BotDetect PHP Captcha protection to your Laravel MVC applications requires a slightly different approach than adding it to basic PHP websites, but is still straightforward. This page will guide you through the necessary steps and explain the available options.

First Time Here?

Check the BotDetect Laravel 5.0 Captcha Quickstart for key integration steps.

Prerequisites

Table of Contents

The BotDetect Laravel CAPTCHA Integration Package

Laravel is a MVC framework that leverages certain conventions to provide a rich set of functionality to PHP application developers. Therefore adding BotDetect Captcha into Laravel based site or application requires a layer of integration code to conform to those conventions. This enables BotDetect Captcha to integrate seamlessly and be used according to expectations of Laravel developers.

Path Aliases Used Throughout This Guide

  • <MY_LARAVEL_WEBROOT>: the root of the application install (same as the base_path() Laravel helper)
  • <MY_LARAVEL_APP>: the app directory (same as the app_path() Laravel helper)
  • <BD_LARAVEL_PACK>: the downloaded and extracted contents of the BotDetect Laravel Captcha Integration Package

For convenience purposes we are providing the BotDetect Captcha Laravel integration code packaged as a Laravel composer package.

You can get the whole BotDetect Laravel Captcha integration package here. The package contains the integration code, basic Captcha validation example, an example demonstrating the usage of the BotDetect Captcha with Laravel Validation class and Blade syntax. There is also an example of adding BotDetect Captcha into Laravel Auth Login and Register forms.

The BotDetect Laravel CAPTCHA Composer Package

BotDetect Laravel CAPTCHA composer package, is available at https://packagist.org/packages/captcha-com/laravel-captcha

The integration package includes a wrapper class around the regular BotDetect Captcha Library for use in your application Controllers.

The package also includes separate Controllers that handle:

  • Captcha image and sound requests, which use
    http://<MY_LARAVEL_WEBROOT>/public/captcha_handler Urls by default.
  • Captcha resources, which use
    http://<MY_LARAVEL_WEBROOT>/public/captcha_resource/get Urls by default.

Laravel Basic BotDetect CAPTCHA Example

This basic Laravel 5.0 Captcha example shows how to use the BotDetect Captcha Laravel composer package in your Controller and View code, and handling of basic Captcha user input validation.

  • Routing: <BD_LARAVEL_PACK>/bd-captcha-laravel-5.0-examples /app/Http/routes.php
  • Controller: <BD_LARAVEL_PACK>/bd-captcha-laravel-5.0-examples /app/Http/Controllers/ExampleController.php
  • View: <BD_LARAVEL_PACK>/bd-captcha-laravel-5.0-examples /resources/views/example.blade.php
  • Captcha configuration options: <BD_LARAVEL_PACK>/bd-captcha-laravel-5.0-examples/config/captcha_config/ExampleCaptchaConfig.php

Form Validation BotDetect Laravel CAPTCHA Example

This Laravel 5.0 form validation Captcha example shows how to use BotDetect Captcha with Laravel form and validation functionality by implementing a simple contact form.

  • Routing: <BD_LARAVEL_PACK>/bd-captcha-laravel-5.0-examples /app/Http/routes.php
  • Controller: <BD_LARAVEL_PACK>/bd-captcha-laravel-5.0-examples /app/Http/Controllers/ContactController.php
  • View: <BD_LARAVEL_PACK>/bd-captcha-laravel-5.0-examples /resources/views/contact.blade.php
  • Captcha configuration options: <BD_LARAVEL_PACK>/bd-captcha-laravel-5.0-examples/config/captcha_config/ContactCaptchaConfig.php

Laravel Auth BotDetect CAPTCHA Example

This Laravel 5.0 Auth Captcha example shows how to use BotDetect Captcha with Laravel Authentication.

  • Routing: <BD_LARAVEL_PACK>/bd-captcha-laravel-5.0-examples /app/Http/routes.php
  • Controller:
    • <BD_LARAVEL_PACK>/bd-captcha-laravel-5.0-examples/app/Http /Controllers/Auth/AuthController.php
    • <BD_LARAVEL_PACK>/bd-captcha-laravel-5.0-examples/app/Http /Controllers/Auth/PasswordController.php
  • View:
    • <BD_LARAVEL_PACK>/bd-captcha-laravel-5.0-examples/resources /views/auth/login.blade.php
    • <BD_LARAVEL_PACK>/bd-captcha-laravel-5.0-examples/resources /views/auth/register.blade.php
    • <BD_LARAVEL_PACK>/bd-captcha-laravel-5.0-examples/resources /views/auth/password.blade.php
  • Captcha configuration options:
    • <BD_LARAVEL_PACK>/bd-captcha-laravel-5.0-examples/config /captcha_config/LoginCaptchaConfig.php
    • <BD_LARAVEL_PACK>/bd-captcha-laravel-5.0-examples/config /captcha_config/RegisterCaptchaConfig.php
    • <BD_LARAVEL_PACK>/bd-captcha-laravel-5.0-examples/config /captcha_config/ResetPasswordCaptchaConfig.php

The provided examples are available inside of a single Laravel app via their respective controllers:

   http://<MY_LARAVEL_WEBROOT>/public/example    http://<MY_LARAVEL_WEBROOT>/public/contact    http://<MY_LARAVEL_WEBROOT>/public/auth/login    http://<MY_LARAVEL_WEBROOT>/public/auth/register    http://<MY_LARAVEL_WEBROOT>/public/password/email

You can copy the whole preconfigured Laravel app from the BotDetect Captcha Laravel Package somewhere on your development web server and examine it there.

1. Include BotDetect CAPTCHA in Your Laravel MVC Application

Install BotDetect Laravel CAPTCHA composer package via Composer

Note: If you do not have Composer yet, you can install it by following the instructions on https://getcomposer.org

If you have Git installed on your development machine, you should use the following installation procedure:

Step 1: Install the BotDetect Laravel Captcha Composer Package

Run the following command in your application's root directory:

Step 2: Register the Laravel Captcha service provider (<MY_LARAVEL_WEBROOT>/config/app.php):

"providers" => [
  ...
  "LaravelCaptcha\Providers\LaravelCaptchaServiceProvider"
]

A Note On PHP Session Persistence

The BotDetect Captcha Library requires persistent per-user server storage to work properly. By default, it uses standard PHP Sessions, which is convenient in most use cases.

If your environment requires a different approach to handling Session data, you can implement your own Captcha persistence methods via the provided BotDetect Captcha persistence hooks in the lib/botdetect/CaptchaConfig.php file.

Also, the Laravel BotDetect CAPTCHA composer package integration wrapper also calls session_start() when it's called. This provides a safe default that works in most usage scenarios.

If your Laravel application is handling Sessions in a non-standard way (i.e. there is no PHP $_SESSION available), you can implement your own Captcha persistence methods via provided BotDetect Captcha persistence hooks in the lib/botdetect/CaptchaConfig.php file.

2. Display BotDetect CAPTCHA In Your Laravel View

Before displaying the Captcha in your View, the first we need to register HTTP GET and POST verbs in your routes. The next step, the related Controller needs to import the BotDetectCaptcha class and then create an instance of the Captcha class and set a proper name for your Captcha instance. It also needs to pass the Captcha markup to the View, which can then display it alongside other form elements.

Register a route for multiple verbs

Route::get('example', 'ExampleController@getExample');
Route::post('example', 'ExampleController@postExample');

In the code above, we have registered HTTP GET and POST verbs for your page.

Import the BotDetect CAPTCHA class and create an instance

<?php namespace App\Http\Controllers;

use Illuminate\Support\Facades\Request;
// Importing the BotDetectCaptcha class
use LaravelCaptcha\Integration\BotDetectCaptcha;

class ExampleController extends Controller 
{
  // get captcha instance to handle for the example page
  private function getExampleCaptchaInstance()
  {
    // Captcha parameters
    $captchaConfig = [
      'CaptchaId' => 'ExampleCaptcha', // a unique Id for the Captcha instance
      'UserInputId' => 'CaptchaCode', // Id of the Captcha code input textbox
      // The path of the Captcha config file is inside the config folder
      'CaptchaConfigFilePath' => 'captcha_config/ExampleCaptchaConfig.php'
    ];
    return BotDetectCaptcha::GetCaptchaInstance($captchaConfig);
  }

When creating an instance of the Captcha class, it will be supplied a unique name through the CaptchaId setting. Each individual Controller action including Captcha validation should use a unique CaptchaId value to avoid persistence name clashes.

The additional UserInputId setting is used to setup client-side functionality operating on the Captcha code input field.

You may wish to override library settings, e.g. changes the captcha code length, captcha image style or captcha image size, etc... To do that, you need to add CaptchaConfigFilePath setting and then provide the path to your Captcha config file and this file MUST be located in the config folder. You can also put your Captcha config in any folder inside the config folder, in this example we have putted it in the captcha_config folder.

Captcha configuration options

<?php if (!class_exists('CaptchaConfiguration')) { return; }

// BotDetect PHP Captcha configuration options

$LBD_CaptchaConfig = CaptchaConfiguration::GetSettings();

$LBD_CaptchaConfig->CodeLength = 4;
$LBD_CaptchaConfig->ImageWidth = 250;
$LBD_CaptchaConfig->ImageHeight = 50;

In the code above, we have overridden the default settings of library (/config/captcha_config/ExampleCaptchaConfig.php). You can find a full list of available Captcha configuration options and related instructions at the Captcha configuration options page.

Pass the BotDetect CAPTCHA HTML Markup to the Laravel View

The Laravel MVC Captcha composer package generates its own markup, which should be made available to your View. The Captcha Html is retrieved by calling the Html() method on the $captcha object, and then made available to the view by pass an array of data as the second parameter to the view helper (or you can also use the with() method).

<?php namespace App\Http\Controllers;

use Illuminate\Support\Facades\Request;
// Importing the BotDetectCaptcha class
use LaravelCaptcha\Integration\BotDetectCaptcha;

class ExampleController extends Controller 
{
  // get captcha instance to handle for the example page
  private function getExampleCaptchaInstance()
  {
    // Captcha parameters
    $captchaConfig = [
      'CaptchaId' => 'ExampleCaptcha', // a unique Id for the Captcha instance
      'UserInputId' => 'CaptchaCode', // Id of the Captcha code input textbox
      // The path of the Captcha config file is inside the config folder
      'CaptchaConfigFilePath' => 'captcha_config/ExampleCaptchaConfig.php',
    ];
    return BotDetectCaptcha::GetCaptchaInstance($captchaConfig);
  }

  public function getExample() 
  {
    // captcha instance of the example page
    $captcha = $this->getExampleCaptchaInstance();
    
    // passing Captcha Html to example view
    return view('example', ['captchaHtml' => $captcha->Html()]);
  }

}

The Captcha markup is now available inside your View's $captchaHtml variable.

Compose Your Laravel View With BotDetect CAPTCHA Display

Inside your View script, you should include some form elements alongside the Captcha display. In a regular form with a submit button, you need an input field where the user retypes the characters shown in the Captcha image.

You display the image by outputting the $captchaHtml variable from the previous step:

<form action="{{ URL::to('example') }}" method="POST">
  <input type="hidden" name="_token" value="{{ csrf_token() }}">

  <div>{!! $captchaHtml !!}</div>
  <input type="text"id="CaptchaCode" name="CaptchaCode">
  <button type="submit">Submit</button>
</form>

You also need to add the BotDetect Captcha layout stylesheet, which Laravel will include in the <head> of your page containing the Captcha:

<link type="text/css" rel="stylesheet" href="{{ CaptchaUrls::LayoutStylesheetUrl() 
}}">

The Captcha should now be visible and functioning in your View.

3. Validate the CAPTCHA In Your Laravel Controller

After your Captcha is displayed alongside a form input field, you will want to validate user submitted Captcha code in a Controller action. This should always be done before any sensitive processing to confirm the submitted data is actually entered by a person and not a bot.

Validate the Submitted CAPTCHA Code User Input

The validation of Captcha code input should be performed in Controler->Action that is on the receiving end of the form submission (where the form action points to).

Usually, the submitted form data is available inside the Laravel Request object, by the same name you gave the Captcha code input field on the form where it was displayed. For example: Request::input('CaptchaCode').

It is then a matter of calling the Validate() method of the Captcha object and passing it the user input.

// captcha instance of the example page
$captcha = $this->getExampleCaptchaInstance();
$code = Request::input('CaptchaCode');
$isHuman = $captcha->Validate($code);

Handle CAPTCHA Validation Failure / Success

You should then write some code to handle both Captcha validation success and failure. If it failed, you should abort further processing and display an error message; if it succeeded, you can proceed with the protected form action:

if ($isHuman) {
  // TODO: Captcha validation passed:
  // continue with form processing, knowing the submission was made by a human
} else {
  // TODO: Captcha validation failed:
  // abort sensitive action, return an error message
}

This will ensure that the sensitive action can not be automated and is only performed when a human fills out the form.



Please Note

The information on this page is out of date and applies to a deprecated version of BotDetect™ CAPTCHA (v3.0).

An up-to-date equivalent page for the latest BotDetect Captcha release (v4) is BotDetect v4 Captcha documentation index.

General information about the major improvements in the current BotDetect release can be found at the What's New in BotDetect v4.0 page.