Korzen
Bot Protection
In these docs

PHP and Symfony

Bot Protection in PHP without a framework or with Symfony: the tag, Korzen's PHP package for the call on HttpFoundation's request, and trusted proxies.

This guide is for PHP 8.2 and later; for Laravel, see Laravel, and for Slim, Mezzio or another PSR-15 stack, the package's Middleware. Korzen's package for PHP, korzen/bot-protection, asks /v1/decide, gives up at your timeout and lets the visitor through on any error. Its Protect works on Symfony HttpFoundation's request and response, which Symfony uses and plain PHP can add.

Payment, login and sign-up routes: turn on protectedAction: true, so a script that never loads your page cannot take the action. Protecting a checkout

The tag

Put the tag in the <head> of the layout your sign-up, sign-in and checkout pages use (in Symfony, templates/base.html.twig):

<script src="https://eu.korzen.dev/v1/tag.js" data-site-key="YOUR_SITE_KEY" async></script>

For visitors whose network blocks Korzen's host, firstParty: true serves the tag and its beacon from your own domain. First-party mode

The call

Behind Cloudflare? A Worker can do this without changing your app. Cloudflare Workers

Install the package with Composer; without a framework, add HttpFoundation too:

composer require korzen/bot-protection symfony/http-foundation

Load the curl extension where you can: the call then bounds the whole of its time, the name lookup included, by your timeout. Without it, a socket of PHP's own bounds all but the lookup.

Without a framework

In the script that creates the account, handle asks before your code runs, answers a block itself, and leaves the answer in the request's korzen.decision attribute, or null when there is none:

<?php
// public/signup.php
require __DIR__ . '/../vendor/autoload.php';

use Korzen\BotProtection\Client;
use Korzen\BotProtection\Ip;
use Korzen\BotProtection\Laravel\Protect; // any HttpFoundation stack, not Laravel's alone
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

// The timeout for your server's region: https://korzen.dev/bot-protection/docs/server-call#latency
$korzen = new Client((string) getenv('KORZEN_API_KEY'), url: 'https://eu.korzen.dev', timeoutMs: 200);
$protect = new Protect(
    $korzen,
    ip: Ip::socket(...), // nothing in front of PHP; behind a proxy, see "The visitor's IP"
    protectedAction: true, // sign-up, login and payment: a script that never loaded your page holds no token; a page load spends none
    onBlock: fn () => new Response('We could not create your account.', 400),
);

$protect->handle(Request::createFromGlobals(), function (Request $request): Response {
    if ($request->getMethod() !== 'POST') {
        return new Response(render_signup_form()); // your own code
    }
    $decision = $request->attributes->get('korzen.decision'); // a Decision, or null
    $user = create_account($request->request->all()); // your own code
    save_request_id($user, $decision?->requestId); // see "Apply the action"

    return new RedirectResponse('/welcome', 303);
}, '/signup')->send();

The (string) keeps the script running when the key is unset: an empty key is answered 401 on every call, which lets the visitor through, as any failure does.

Symfony

Make the client and Protect services, then call handle from the controller:

# config/services.yaml
services:
    Korzen\BotProtection\Client:
        arguments:
            $apiKey: '%env(KORZEN_API_KEY)%'
            $url: 'https://eu.korzen.dev'
            # The timeout for your server's region: https://korzen.dev/bot-protection/docs/server-call#latency
            $timeoutMs: 200
    Korzen\BotProtection\Laravel\Protect:
        arguments:
            $client: '@Korzen\BotProtection\Client'
            $ip: ['Korzen\BotProtection\Ip', 'lastForwarded'] # one proxy of yours in front: see "The visitor's IP"
            $protectedAction: true # a script that never loaded your page holds no token
<?php
// src/Controller/SignupController.php
namespace App\Controller;

use Korzen\BotProtection\Laravel\Protect;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

final class SignupController extends AbstractController
{
    #[Route('/signup', methods: ['POST'])]
    public function signup(Request $request, Protect $protect): Response
    {
        return $protect->handle($request, function (Request $request): Response {
            $decision = $request->attributes->get('korzen.decision'); // a Decision, or null
            $user = $this->accounts->create($request->request->all()); // your own code
            $user->setKorzenRequestId($decision?->requestId); // see "Apply the action"

            return $this->redirect('/welcome', 303);
        }, '/signup');
    }
}

To ask without Protect, $korzen->decide(DecideRequest::from($request, Ip::socket($request))->withPath('/signup')->withProtectedAction(true)) returns a Decision, or null on any error; it never throws. The package sends the request's headers in the order they came, as $_SERVER keeps them (it reverses PHP-FPM's, which lists them last first); behind nginx, a load balancer or Cloudflare, that is the order the last hop forwards them in.

The visitor's IP

Ip::socket(...) is the connection's address: the visitor's when nothing stands in front of PHP, and your proxy's when you have one. Behind one load balancer or nginx of yours, pass Ip::lastForwarded(...), the entry your proxy added to X-Forwarded-For; behind Cloudflare, Ip::cloudflare(...), which reads CF-Connecting-IP, if your server only takes traffic from Cloudflare. With more proxies in Symfony, set trusted_proxies and pass a function that returns $request->getClientIp(): it reads X-Forwarded-For from the right and skips the addresses you trust. PHP-FPM opens a new connection for each request it serves, so each call carries a TLS handshake: from far from Europe, choose a timeout with room for it.

Apply the action

Protect applies action: on block it answers 403, or what your onBlock returns, and your code never runs. Make that answer the error the form shows when it fails for any other reason, so a bot learns nothing. The account starts in monitor mode, where action is always allow: nothing changes for visitors until you turn on block mode.

Keep the answer's request_id with what the action created, such as the account or the order: it names that decision when you ask us about it. The answer

Test it on your machine

Run php -S localhost:8000 -t public (in Symfony, symfony serve) and open it on localhost. Pages on localhost always accept the tag and are never listed as a domain. Locally the IP is 127.0.0.1 or ::1, and that is fine.

  1. Set KORZEN_API_KEY in the environment and open the sign-up page. In the browser's developer tools, the _kz cookie appears after a few seconds.
  2. Sign up. The decision shows on the dashboard's Decisions page, under the path you sent.
  3. Check fail open: set a wrong key and sign up again. The call answers 401, and the sign-up goes through.

Common mistakes

  • The first entry of X-Forwarded-For. The visitor writes it, so a bot picks its own IP.
  • Ip::lastForwarded(...) with no proxy of yours in front. The visitor then writes the last entry too, and a bot picks its own IP.
  • Calling /v1/decide from the browser. The API key would reach every visitor; the call belongs on your server.
  • A line in your log that starts korzen: the visitor's IP sent to Bot Protection. The client writes it once, at the first decision whose IP is your own network's (a load balancer's, a proxy's, a container's), which Bot Protection judges as no IP: set ip to the visitor's address (the visitor's IP). In Docker on your machine it is the bridge's address, and harmless there.