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
- BotDetect Laravel CAPTCHA download package
- Include BotDetect CAPTCHA in your Laravel application
- Display BotDetect CAPTCHA In Your Laravel View
- Validate the Captcha in your Laravel Controller
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 thebase_path()
Laravel helper)<MY_LARAVEL_APP>
: the app directory (same as theapp_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'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>/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/captcha.php
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/captcha.php
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/captcha.php
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 ]
A Note On PHP Session Persistence
The Laravel CAPTCHA Package requires persistent per-user server storage to work properly. By default, it uses Laravel Session, which is convenient in most use cases.
If your environment requires a different approach to handle Session data, you can be easily adding a custom session driver as described here.
Note that a Session cleanup right after creating a Captcha class instance may cause an error since BotDetect will not find its Session data.
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
<?php if (!class_exists('CaptchaConfiguration')) { return; } // BotDetect PHP Captcha configuration options return [ // Captcha configuration for example page 'ExampleCaptcha' => [ 'UserInputID' => 'CaptchaCode', 'ImageWidth' => 250, 'ImageHeight' => 50, ], ];
In order to use the Laravel CAPTCHA Package, you must declare Captcha configuration in config/captcha.php
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.
In case you need different Captcha for another form in your application, here is the example how to add additional captcha configuration for a login form:
<?php if (!class_exists('CaptchaConfiguration')) { return; } // BotDetect PHP Captcha configuration options return [ // Captcha configuration for example page 'ExampleCaptcha' => [ 'UserInputID' => 'CaptchaCode', 'ImageWidth' => 250, 'ImageHeight' => 50, ], // Captcha configuration for login page 'LoginCaptcha' => [ 'UserInputID' => 'CaptchaCode', 'CodeLength' => CaptchaRandomization::GetRandomCodeLength(4, 6), 'ImageStyle' => [ ImageStyle::Radar, ImageStyle::Collage, ImageStyle::Fingerprints, ], ], ];
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 captcha_image_html()
helper function. It is required to pass a captcha configuration key defined in config/captcha.php
file (as in this example, we have passed the ExampleCaptcha
):
<form action="{{ url('/example') }}" method="POST"> {!! csrf_field() !!} {!! captcha_image_html('ExampleCaptcha') !!} <input type="text"id="CaptchaCode" name="CaptchaCode"> <button type="submit">Submit</button> </form>
You also need to add the BotDetect Captcha layout stylesheet by calling the captcha_layout_stylesheet_url()
helper function, which Laravel will include in the <head>
of your page containing the Captcha:
<link href="{{ captcha_layout_stylesheet_url() }}" type="text/css" rel="stylesheet">
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_captcha
validation rule
$this->validate($request, [ ... 'CaptchaCode'=> 'valid_captcha' ]);
Laravel CAPTCHA package provides valid_captcha
validation rule, simple and convenient facility for validating captcha code in your form.
Use the 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 captcha_validate()
helper function and passing it the user input.
$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.
Current BotDetect Versions
-
BotDetect ASP.NET CAPTCHA
2019-07-22v4.4.2 -
BotDetect Java CAPTCHA
2019-07-22v4.0.Beta3.7 -
BotDetect PHP CAPTCHA
2019-07-22v4.2.5