Laravel 4.2 Basic BotDetect CAPTCHA Example

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 4.2 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 4.2 CAPTCHA basic Captcha validation screenshot

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

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

Routing – /app/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.

Config – /app/config/captcha.php

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

// BotDetect PHP Captcha configuration options

return array(
  // Captcha configuration for example page
  'ExampleCaptcha' => array(
    'UserInputID' => 'CaptchaCode',
    'ImageWidth' => 250,
    'ImageHeight' => 50,
  ),

);

In order to use the Laravel CAPTCHA Package, we have declared Captcha configuration which will be used when showing Captcha image in example view. Detailed description of this approach is available in a BotDetect Laravel 4.2 integration guide.

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

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title>Laravel Basic BotDetect CAPTCHA Example</title>
  {{ HTML::style('css/bootstrap.min.css') }}

  <!-- include the BotDetect layout stylesheet -->
  {{ HTML::style(captcha_layout_stylesheet_url()) }}

  <style type="text/css">
    body { padding: 70px 0 }
    .container{ width: 980px !important }
  </style>
</head>
<body>
    <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
   <div class="container">
    <div class="navbar-header">
     <a class="navbar-brand" href="#">BotDetect Captcha</a>
    </div>
    <div id="navbar" class="navbar-collapse collapse">
     <ul class="nav navbar-nav navbar-right">
         <li>{{ HTML::link('example', 'Basic Example') }}</li>   
       <li>{{ HTML::link('contact', 'Form Example') }}</li>  
     </ul>
    </div><!--/.nav-collapse -->
   </div>
  </nav>


   <div class="container">
   
      <h3>Laravel Basic BotDetect CAPTCHA Example</h3><hr>

      @if (Session::has('status'))
    <div class="alert alert-success">
     {{ Session::get('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::open(array('url' => 'example')) }}

      <div class="form-group">
        <!-- Captcha image html -->
        {{ captcha_image_html('ExampleCaptcha') }}
      </div>

      <div class="row">
        <div class="form-group col-sm-4">
          {{ Form::label('CaptchaCode', 'Retype the characters from the picture') }}

          <!-- Captcha code user input textbox -->
          {{ Form::text('CaptchaCode', null, array(
              'id' => 'CaptchaCode',
              'class' => 'form-control'
            ))
          }}
        </div>
      </div>

      {{ Form::submit('Submit', array('class' => 'btn btn-primary')) }}

      {{ Form::close() }}
  </div>
</body>
</html>

The above code uses the Laravel Forms & HTML and the Blade syntax to generate a form, although the actual form can be created in many other ways. 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 View uses the captcha_image_html() helper function to generate Captcha image. It is required to pass a captcha configuration key defined in app/config/captcha.php file. The View also needs to add the required stylesheet of the library by calling captcha_layout_stylesheet_url() helper function and prints out a message about the Captcha validation status (set in the Controller).

Controller – /app/controllers/ExampleController.php

<?php

class ExampleController extends BaseController {

  public function getExample() {
    return View::make('example');
  }

  public function postExample() {
    // validate the user-entered Captcha code when the form is submitted
    $code = Input::get('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::to('example')
             ->with('status', 'CAPTCHA validation passed, human visitor confirmed!');
    }

    // Captcha validation failed, return an error message
    return Redirect::to('example')
            ->withErrors(array('CaptchaCode' => 'CAPTCHA validation failed, please try again.'));
  }

}

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

The example form submits the data to the postExample() action, which is where we check the submitted data and pass it to the captcha_validate() helper function.