middlewares/honeypot

Middleware to implement a honeypot spam prevention

v1.2.0 2018-08-18 10:57 UTC

README

Latest Version on Packagist Software License Build Status Quality Score Total Downloads SensioLabs Insight

Middleware to implement a honeypot spam prevention. This technique is based on creating a input field that should be invisible and left empty by real users but filled by most spam bots. The middleware check in the incoming requests whether this value exists and is empty (is a real user) or doesn't exist or has a value (is a bot) returning a 403 response.

Requirements

Installation

This package is installable and autoloadable via Composer as middlewares/honeypot.

composer require middlewares/honeypot

Example

$dispatcher = new Dispatcher([
	new Middlewares\Honeypot(),

    function ($request) {
        $response = new Response();
        //Use Honeypot::getField() to generate honeypot fields
        $response->getBody()->write('<form>'.Honeypot::getField().'</form>');
        return $response;
    }
]);

$response = $dispatcher->dispatch(new ServerRequest());

Options

__construct(string $name = "hpt_name")

The name of the input field (by default is "hpt_name"). You can use the name to hide the input using css:

input[name="hpt_name"] {
    display: none;
}

responseFactory(Psr\Http\Message\ResponseFactoryInterface $responseFactory)

A PSR-17 factory to create 403 responses.

Helpers

Honeypot::getField($name = null)

This static method is provided to ease the creation of the input field, accepting an optional $name argument. If it's not provided, use the same name passed previously to the middleware.

Example:

<html>
    <head>
        <style type="text/css">
            input[name="hpt_name"] { display: none; }
        </style>
    </head>
    <body>
        <form method="POST">
            <?= Middlewares\Honeypot::getField() ?>
            <label>
                User:
                <input type="text" name="username">
            </label>
            <label>
                Password:
                <input type="password" name="password">
            </label>
        </form>
    </body>
</html>

Honeypot::getHiddenField($name = null)

This static method generates the input field just like getField() does, but adds inline CSS to hide the field directly. Note: This may be easier to detect for some bots. If you want to get creative with hiding the field, use getField() in combination with custom CSS (or JS).

Please see CHANGELOG for more information about recent changes and CONTRIBUTING for contributing details.

The MIT License (MIT). Please see LICENSE for more information.