Laravel 5.0 Basic BotDetect CAPTCHA Example (BotDetect v3.0; deprecated)

Laravel Basic BotDetect CAPTCHA Example illustrates the most basic form of BotDetect PHP Captcha protection in Laravel MVC applications.

First Time Here?

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

Alongside the Captcha image, the user is provided with an input field to retype the displayed characters. Depending on if the Captcha code entered matches the displayed one or not, a message stating the validation result is shown on the form.

The simple code showing the message in this example would of course be replaced with useful form processing code in a real world scenario.

BotDetect Laravel 5.0 CAPTCHA basic Captcha validation screenshot

Files for this ('bd-captcha-laravel-5.0-examples') example are:

The files are available for download as a part of the BotDetect Captcha Laravel integration package.

Routing – /app/Http/routes.php

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

In the code above we have registered HTTP GET and POST verbs for the example page. On HTTP GET request to the example page, the getExample() action of the ExampleController is executed, while on a HTTP POST request to the example page, the postExample() action of the ExampleController is executed.

View – /resources/views/example.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Laravel Basic BotDetect CAPTCHA Example</title>
  <link href="{{ URL::asset('css/bootstrap.min.css') }}" type="text/css" 
  rel="stylesheet">
  
  <!-- include the BotDetect layout stylesheet -->
  <link href="{{ CaptchaUrls::LayoutStylesheetUrl() }}" type="text/css" 
  rel="stylesheet">
</head>
<body>
  <nav class="navbar navbar-default">
    <div class="container-fluid">
      <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" 
        data-target="#bs-example-navbar-collapse-1">
          <span class="sr-only">Toggle Navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" href="#">BotDetect Captcha</a>
      </div>

      <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
        <ul class="nav navbar-nav navbar-right">
          <li><a href="{{ URL::to('example') }}">Basic Example</a></li>
          <li><a href="{{ URL::to('contact') }}">Form Example</a></li>
        </ul>
      </div>
    </div>
  </nav>

  <div class="container-fluid">
  <div class="row">
    <div class="col-md-8 col-md-offset-2">
      <div class="panel panel-default">
        <div class="panel-heading">Basic Example</div>
        <div class="panel-body">

          @if (session('status'))
            <div class="alert alert-success">
              {{ session('status') }}
            </div>
          @endif

          @if (count($errors) > 0)
            <div class="alert alert-danger">
              <strong>Whoops!</strong> There were some problems with your input
              .<br><br>
              <ul>
                @foreach ($errors->all() as $error)
                  <li>{{ $error }}</li>
                @endforeach
              </ul>
            </div>
          @endif
          
          <form class="form-horizontal" role="form" method="POST" 
          action="{{ URL::to('example') }}">
            <input type="hidden" name="_token" value="{{ csrf_token() }}">

            <div class="form-group">
              <div class="col-md-6 col-md-offset-4">
                <!-- Captcha image html-->
                {!! $captchaHtml !!}
              </div>
              <div class="col-md-6 col-md-offset-4">
                <!-- Captcha code user input textbox -->
                <input type="text" class="form-control" id="CaptchaCode" 
                name="CaptchaCode" style="width: 276px; margin-top: 5px">
              </div>
            </div>

            <div class="form-group">
              <div class="col-md-6 col-md-offset-4">
                <button type="submit" class="btn btn-primary">
                  Submit
                </button>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>

  <!-- Scripts -->
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/
  js/bootstrap.min.js"></script>
</body>
</html>

The above code uses the Laravel Blade syntax to generate Captcha image. The only requirement is that the form contains an input field of your choice where the user can retype the characters shown in the Captcha image. This user-entered code should be available to you in Controller code after form submission.

You should ensure that the form action points to the Controller action of the View to which it belongs to. Also, the name of the input field corresponds to the variable in the request object that we will use for Captcha validation in the Controller.

The Captcha markup made available in the Controller is used in the View to compose a simple form with one input field and a Captcha image. The View need to add the required stylesheet of the library, and it also prints out a message about the Captcha validation status (set in the Controller).

Controller – /app/Http/Controllers/ExampleController.php

<?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()]);
  }

  public function postExample() 
  {
    // captcha instance of the example page
    $captcha = $this->getExampleCaptchaInstance();
    
    // validate the user-entered Captcha code when the form is submitted
    $code = Request::input('CaptchaCode');
    $isHuman = $captcha->Validate($code);

    if ($isHuman) 
    {
      // Captcha validation passed
      // TODO: continue with form processing, knowing the submission was made by a human
      return redirect()
          ->back()
          ->with('status', 'CAPTCHA validation passed, human visitor confirmed!'); 
    }
    
    // Captcha validation failed, return an error message
    return redirect()
      ->back()
      ->withErrors(['CaptchaCode' => 'CAPTCHA validation failed, please try again.']);
  }
}

The example Controller follows the basic instructions from the BotDetect Laravel 5.0 Captcha integration guide.

First, we need to create a function to get an instance of the Captcha class called getExampleCaptchaInstance(), and then the Html required for displaying the Captcha image and integrated controls is 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).

The example form submits the data to the postExample() action, which is where we check the submitted data and pass it to the Validate() method of the $captcha object.

Captcha configuration options – /config/captcha_config/ExampleCaptchaConfig.php

<?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. You can find a full list of available Captcha configuration options and related instructions at the Captcha configuration options page.



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.