Skip to content

Documentation

Fabian Wennink edited this page Sep 24, 2023 · 4 revisions

This is documentation (work in process) for the upcoming release of IconCaptcha 4.

Requirements

Database support

In order to use one of the provided database storage drivers, ensure these requirements are met.

Installation

Composer

Install IconCaptcha with Composer by using the following command.

composer require fabianwennink/iconcaptcha

Manual

  1. Download IconCaptcha for PHP.
  2. Download the IconCaptcha client-side package.
  3. Unpack both repositories to somewhere on your computer.
  4. Drag the content of the dist/ folder of the IconCaptcha client-side package into the assets/ folder of the IconCaptcha PHP package.
  5. Check the assets/ folder and make sure you see the following sub-folders: css/, icons/ and js/.

Note: To make it easier to try out the example captchas, the client-side package is already included in this repository. However, these files might not always be up-to-date. To ensure you always have the latest version, please follow the instructions above.

Implementation

1. HTML

Add the IconCaptcha widget inside the form you wish to protect. The widget will be generated inside this element. Use the data-theme attribute to specify which theme should be used. By default, IconCaptcha comes with 2 themes: light and dark. If no theme is given, IconCaptcha will default to the light theme.

To further improve the security of your form, a CSRF token may be added as shown in the example. Note that if you can't run PHP in your HTML page, this feature will not function and should be disabled in the IconCaptcha configuration (by setting the token option to false).

<form method="post">

    <!-- The IconCaptcha widget will be rendered in this element -->
    <div class="iconcaptcha-widget" data-theme="light"></div>
    
    <!-- Additional security token to prevent CSRF. Optional but highly recommended - disable in config. -->
    <?php echo \IconCaptcha\Token\IconCaptchaToken::render(); ?>

</form>

<!-- Include the IconCaptcha assets - Change the paths according to your installation -->
<link href="/path/to/assets/css/icon-captcha.min.css" rel="stylesheet" type="text/css">
<script src="/path/to/assets/js/icon-captcha.min.js" type="text/javascript"></script>

2. PHP

The following code processes every captcha request and can be found in captcha-request.php. It must be accessible as an endpoint to be used in the client-side. In the JavaScript code, this endpoint must be specified in the validationPath configuration option. The captcha-config.php script loaded in the example below contains the IconCaptcha configuration and must be included before the IconCaptcha class is called.

If you haven't installed installed IconCaptcha with Composer, make sure you still load the autoloader included in the downloaded ZIP.

<?php

require_once __DIR__ . '/../vendor/autoload.php';

use IconCaptcha\IconCaptcha;

try {

    // Start a session.
    // Note: check the documentation to see whether you need this.
    session_start();

    // Load the IconCaptcha options.
    $options = require 'captcha-config.php';

    // Create an instance of IconCaptcha.
    $captcha = new IconCaptcha($options);

    // Handle the CORS preflight request.
    $captcha->handleCors();

    // Process the request.
    $captcha->request()->process();

    // Request was not supported/recognized.
    http_response_code(400);

} catch (Throwable $exception) {

    http_response_code(500);

    // ADD YOUR CUSTOM ERROR LOGGING SERVICE HERE.

}

3. JavaScript

To render the IconCaptcha widget, the following code should be added to the page. Both plain JavaScript and jQuery are supported and function exactly the same. Use the implementation you prefer. An example for jQuery can be found further down.

<script type="text/javascript">
    
    // JavaScript implementation.
    document.addEventListener('DOMContentLoaded', function() {
        IconCaptcha.init('.iconcaptcha-widget', {
            general: {
                validationPath: '/path/to/captcha-request.php', // required, change path according to your installation.
                fontFamily: 'inherit',
                credits: 'show',
            },
            security: {
                clickDelay: 500,
                hoverDetection: true,
                enableInitialMessage: true,
                initializeDelay: 500,
                selectionResetDelay: 3000,
                loadingAnimationDelay: 1000,
            },
            messages: {
                initialization: {
                    verify: 'Verify that you are human.',
                    loading: 'Loading challenge...',
                },
                header: 'Select the image displayed the <u>least</u> amount of times',
                correct: 'Verification complete.',
                incorrect: {
                    title: 'Uh oh.',
                    subtitle: "You've selected the wrong image.",
                },
                timeout: {
                    title: 'Please wait.',
                    subtitle: 'You made too many incorrect selections.'
                }
            }
        });
    });
</script>

jQuery

If you wisht to use jQuery, make sure that the jQuery library is loaded before initializing IconCaptcha.

<script src="//ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
    
    // IconCaptcha hooks into jQuery, if you rather use jQuery instead of plain JavaScript.
    // Note that the jQuery library should be loaded prior to initializing IconCaptcha.
    $(document).ready(function() {
        $('.iconcaptcha-widget').iconCaptcha({
            // The captcha options go here like demonstrated in the example above.
        })
    });
</script>

Database

TODO


Messages

The following strings will be used by IconCaptcha, and can be changed to your liking.

Javascript

See the JavaScript implementation example at the 'Usage' section to see how to set these messages.

Message Default value
messages.header Select the image displayed the <u>least</u> amount of times
messages.correct Verification complete.
messages.incorrect.title Uh oh.
messages.incorrect.subtitle You've selected the wrong image.
messages.timeout.title Please wait.
messages.timeout.subtitle You made too many incorrect selections.
messages.initialization.verify Verify that you are human.
messages.initialization.loading Loading challenge...

Events

Events will be triggered at various point in the client-side code. You can use a custom script to hook into the events and execute your own code if necessary. Note that you should not rely on these events, as these are purely client-side and can be triggered manually by attackers. ALWAYS PERFORM THE SERVER-SIDE VALIDATION!

Event Description
init Fires when the IconCaptcha has been fully built and the image details have been requested from the server.
selected Fires when the user selects an icon, regardless of if the icon is correct or not.
refreshed Fires when the user selected an incorrect icon and IconCaptcha is done refreshing it's challenge.
timeout Fires when the user made too many incorrect selections and the captcha is in timeout mode for a period of time.
invalidated Fires when the IconCaptcha invalidated itself after a period of time without user interaction.
reset Fires when the a captcha instance was manually reset using the reset function.
success Fires when the user selected the correct icon.
error Fires when the user selected the incorrect icon.

Hooks

TODO

Reset a widget

It is possible to manually reset a specific captcha widget, and even every captcha widget present on the webpage.

To do so, simply call the IconCaptcha.reset() function from within your custom JavaScript code. This will reset every rendered widget on the page. If you only wish to target a specific widget, pass the widget identifier to the reset function, e.g. IconCaptcha.reset('5fd3c68181999b447d4c89df5818e8e3ed9142dc').

Validation errors

TODO