How to Add BotDetect PHP CAPTCHA Protection to Laravel 5.6 Applications

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.6 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 demostrating the usage of the BotDetect Captcha with Laravel's Validation class and Blade Templates. 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, sound, and resources requests, which use
    http://<MY_LARAVEL_WEBROOT>/simple-captcha-handler Urls by default.

Laravel Basic BotDetect CAPTCHA Example

This basic Laravel 5.6 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.6-examples/routes/web.php
  • Controller: <BD_LARAVEL_PACK>/bd-captcha-laravel-5.6-examples /app/Http/Controllers/ExampleController.php
  • View: <BD_LARAVEL_PACK>/bd-captcha-laravel-5.6-examples /resources/views/example.blade.php
  • Config: <BD_LARAVEL_PACK>/bd-captcha-laravel-5.6-examples/config/botdetect.xml

Form Validation BotDetect Laravel CAPTCHA Example

This Laravel 5.6 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.6-examples/routes/web.php
  • Controller: <BD_LARAVEL_PACK>/bd-captcha-laravel-5.6-examples /app/Http/Controllers/ContactController.php
  • View: <BD_LARAVEL_PACK>/bd-captcha-laravel-5.6-examples /resources/views/contact.blade.php
  • Config: <BD_LARAVEL_PACK>/bd-captcha-laravel-5.6-examples /config/botdetect.xml

Laravel Auth BotDetect CAPTCHA Example

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

  • Routing: <BD_LARAVEL_PACK>/bd-captcha-laravel-5.6-examples/routes/web.php
  • Controller:
    • <BD_LARAVEL_PACK>/bd-captcha-laravel-5.6-examples/app/Http /Controllers/Auth/LoginController.php
    • <BD_LARAVEL_PACK>/bd-captcha-laravel-5.6-examples/app/Http /Controllers/Auth/RegisterController.php
    • <BD_LARAVEL_PACK>/bd-captcha-laravel-5.6-examples/app/Http /Controllers/Auth/ForgotPasswordController.php
  • View:
    • <BD_LARAVEL_PACK>/bd-captcha-laravel-5.6-examples/resources/views /auth/login.blade.php
    • <BD_LARAVEL_PACK>/bd-captcha-laravel-5.6-examples/resources/views /auth/register.blade.php
    • <BD_LARAVEL_PACK>/bd-captcha-laravel-5.6-examples/resources/views /auth/passwords/email.blade.php
  • Config:
    • <BD_LARAVEL_PACK>/bd-captcha-laravel-5.6-examples/config/botdetect.xml

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

http://<MY_LARAVEL_WEBROOT>/example
http://<MY_LARAVEL_WEBROOT>/contact
http://<MY_LARAVEL_WEBROOT>/login
http://<MY_LARAVEL_WEBROOT>/register
http://<MY_LARAVEL_WEBROOT>/password/reset

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::class
]

2. Display BotDetect CAPTCHA In Your Laravel View

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.

Captcha configuration options

<?xml version="1.0" encoding="UTF-8"?>
<botdetect xmlns="https://captcha.com/schema/php"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://captcha.com/schema/php
     https://captcha.com/schema/php/botdetect-4.2.3.xsd">

  <captchaStyles>
    <captchaStyle>
      <name>ExampleCaptcha</name>
      <userInputID>CaptchaCode</userInputID>
      <codeLength>4-6</codeLength>
    </captchaStyle>
  </captchaStyles>

</botdetect>

In order to use the Laravel CAPTCHA Package, you must delare Captcha configuration in config/botdetect.xml file following the structure given above. The ExampleCaptcha is an example name and will be used when showing Captcha image in your view, you should pick a name that best matches your usage scenario like: LoginCaptcha, ContactCaptcha, etc. You can find a full list of available Captcha configuration options and related instructions at the Captcha configuration options page.

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 calling the simple_captcha_image_html() helper function. It is required to pass a captcha style name defined in config/botdetect.xml file (as in this example, we have passed the ExampleCaptcha):

<form action="{{ url('/example') }}" method="POST">
  {!! csrf_field() !!}

  {!! simple_captcha_image_html('ExampleCaptcha') !!}
  <input type="text"id="CaptchaCode" name="CaptchaCode">
  <button type="submit">Submit</button>
</form>

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.

Use the valid_simple_captcha validation rule

$this->validate($request, [
  ...
  'CaptchaCode'=> 'valid_simple_captcha'
]);

Laravel CAPTCHA package provides valid_simple_captcha validation rule, simple and convenient facility for validating captcha code in your form.

Use the simple_captcha_validate() helper function

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's 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 simple_captcha_validate() helper function and passing it the user input.

$code = $request->input('CaptchaCode');
$isHuman = simple_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.