Stop form spam in Symfony

Updated

This guide adds Bot403 to a contact form in Symfony. The browser solves a small proof of work. Then a small service checks the token with one call to the verify API, after the form is valid and before you accept the message. The visitor sees no puzzle, and the script sets no cookie. The free plan covers 5,000 checks a month and needs no card.

The example uses Symfony 8.1.11 on PHP 8.5.12, in the official composer Docker image. On 12 November 2026 it ran against a local stand-in for the verify API that gives the documented answers. A good token went through. A reused token, a filled honeypot and a form with no token were refused. A 402 quota answer, an API that answered with an HTML error page and an API that did not answer let the form through. A wrong secret key refused every form and logged the reason. The two functional tests in "Test it" passed.

Before you start

Sign in. Create a site. Copy its public key (pk_) and its secret key (sk_). Create the app and add the packages:

Terminal
composer create-project symfony/skeleton contact
cd contact
composer require symfony/http-client symfony/form symfony/twig-bundle symfony/validator symfony/security-csrf
composer require --dev symfony/test-pack symfony/browser-kit symfony/css-selector

Declare the secret key in .env with an empty value, and put the real key in .env.local, which Git ignores. When a variable that the config uses is not defined at all, Symfony stops with "Environment variable not found". The tests read .env too, so they need the empty line.

.env and .env.local
# .env
BOT403_SECRET_KEY=

# .env.local
BOT403_SECRET_KEY=sk_live_YOUR_SECRET_KEY

1. The HTTP client

A scoped client keeps the base URL, the secret key and the time limits in one place. Symfony makes it available to autowiring as HttpClientInterface $bot403Client.

config/packages/bot403.yaml
framework:
    http_client:
        scoped_clients:
            bot403.client:
                base_uri: 'https://bot403.com'
                headers:
                    Authorization: 'Bearer %env(BOT403_SECRET_KEY)%'
                timeout: 3
                max_duration: 5

timeout: 3 gives up when no data arrives for 3 seconds. max_duration: 5 caps the whole call at 5 seconds. Without them, the call waits for default_socket_timeout, which is 60 seconds in a default PHP setup.

2. The check

The service posts the top-level text fields of the request to https://bot403.com/api/v1/verify. It returns true when the answer is ok: true, when the reason is quota, or when Bot403 does not answer.

src/Bot403/Bot403Checker.php
<?php

namespace App\Bot403;

use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;

final class Bot403Checker
{
    public function __construct(
        private HttpClientInterface $bot403Client,
        private LoggerInterface $logger,
    ) {
    }

    /** Returns true when the form may go through. */
    public function check(Request $request): bool
    {
        // 1. Post the top-level text fields: _bot403 and the honeypot field.
        //    The fields of the Symfony form (contact[...]) stay on your server.
        $fields = array_filter($request->request->all(), 'is_string');
        try {
            $result = $this->bot403Client
                ->request('POST', '/api/v1/verify', ['body' => $fields])
                ->toArray(false);
        } catch (TransportExceptionInterface|DecodingExceptionInterface $e) {
            $this->logger->error('bot403 did not answer, letting the form through: '.$e->getMessage());

            return true;
        }
        $reason = $result['reason'] ?? '';
        if (\in_array($reason, ['unauthorized', 'rate_limited', 'too_large'], true)) {
            $this->logger->error('bot403 refused the verify call: '.$reason);
        }

        // 2. Refuse when ok is false, except for reason "quota".
        return true === ($result['ok'] ?? null) || 'quota' === $reason;
    }
}

toArray(false) reads the JSON of any answer, also of a 401 or a 402, without an exception. When Bot403 is down and a proxy answers with an HTML page, toArray() throws a decoding exception, and the form goes through.

3. The form and the controller

src/Form/ContactType.php
<?php

namespace App\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints as Assert;

final class ContactType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('email', EmailType::class, ['constraints' => [new Assert\NotBlank(), new Assert\Email()]])
            ->add('message', TextareaType::class, ['constraints' => [new Assert\NotBlank()]]);
    }
}
src/Controller/ContactController.php
<?php

namespace App\Controller;

use App\Bot403\Bot403Checker;
use App\Form\ContactType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

final class ContactController extends AbstractController
{
    #[Route('/contact', name: 'contact', methods: ['GET', 'POST'])]
    public function contact(Request $request, Bot403Checker $bot403): Response
    {
        $form = $this->createForm(ContactType::class);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            if ($bot403->check($request)) {
                // A real visitor: send the email or store the message here
                return $this->redirectToRoute('contact_thanks', [], Response::HTTP_SEE_OTHER);
            }
            $form->addError(new FormError('Send the form again.'));
        }

        // A submitted form with errors gets HTTP 422
        return $this->render('contact.html.twig', ['form' => $form]);
    }

    #[Route('/thanks', name: 'contact_thanks')]
    public function thanks(): Response
    {
        return new Response('Thanks. Your message is on its way.');
    }
}

The check runs only after isValid(). So the CSRF check and your constraints run first, and Bot403 counts only forms that a person could have sent. When the token fails, the form gets an error. render() answers 422 for a submitted form with errors, which Symfony UX Turbo needs to show the error.

templates/contact.html.twig
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Contact</title>
  <script src="https://bot403.com/v1/bot403.js" data-bot403-key="pk_live_YOUR_PUBLIC_KEY" async></script>
</head>
<body>
  {{ form_start(form) }}
    {{ form_errors(form) }}
    {{ form_row(form.email) }}
    {{ form_row(form.message) }}
    <button type="submit">Send</button>
  {{ form_end(form) }}
</body>
</html>

The script tag protects every form on the page. Before the browser sends the form, the script adds a hidden _bot403 field with the token, and a hidden honeypot field (_website by default). Both are top-level fields, next to contact[...].

The trap: only top-level fields go to Bot403

Send the top-level text fields, not the whole request and not the form data. A Symfony form puts its fields under the form name: contact[email], contact[message] and contact[_token]. The script puts _bot403 and the honeypot field at the top level, outside the form. array_filter($request->request->all(), 'is_string') keeps only those top-level strings. The message and the CSRF token stay on your server. In the test run, the stand-in API got only _bot403 and _website.

The same split matters if you build the form without a name, for example with createNamed('', ContactType::class) for a JSON-style API. Then every field is top-level, and Symfony refuses the form with "This form should not contain extra fields.", because it does not know _bot403. Add 'allow_extra_fields' => true to the form options. In the test, the unnamed form was invalid without the option and valid with it.

Stateless CSRF does not stop bots

The current skeleton turns on stateless CSRF for forms, in config/packages/csrf.yaml. It checks that the Origin or Referer header names your own site. In the test run, a POST without either header got 422 with "The CSRF token is invalid. Please try to resubmit the form.", and so did a POST with Origin: https://evil.example.

That stops other sites from posting in the name of your visitor. It does not stop a script that posts to your form and sends your own site in Origin. In the test run, curl with -H "Origin: http://127.0.0.1:8000" passed the CSRF check, and only Bot403 refused it when the token was missing. Keep both.

It also explains why a quick test with curl fails before your code runs: add an Origin header with your own site.

When the secret key is wrong, or Bot403 does not answer

A wrong or missing secret key gets HTTP 401 from the verify API, with the reason unauthorized. The service refuses the form and logs:

Log
[error] bot403 refused the verify call: unauthorized

Every form on the site fails until you fix the key, so look for this line after a deploy. The same line shows rate_limited when the site makes too many verify calls in a minute (100 on the free plan), and too_large for a body over 64 KB.

When Bot403 does not answer, the form goes through, and the log says:

Log
[error] bot403 did not answer, letting the form through: Idle timeout reached for "http://127.0.0.1:9000/api/v1/verify".

That line is from the test run, where the stand-in API ran on port 9000 and waited 30 seconds. The form went through after 3.0 seconds.

Both lines use error() on purpose. Without Monolog, the logger that Symfony uses writes only errors and above to stderr, and drops warnings. In the test run, a warning() call left no line in the log.

Test it

MockHttpClient replaces the scoped client, so the tests need no network and no key. disableReboot() keeps the mock between the GET and the POST.

tests/Controller/ContactControllerTest.php
<?php

namespace App\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\KernelBrowser;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\JsonMockResponse;

final class ContactControllerTest extends WebTestCase
{
    private ?string $sentBody = null;

    private function send(JsonMockResponse $answer, array $extra = ['_bot403' => 'token']): KernelBrowser
    {
        $client = static::createClient();
        $client->disableReboot();
        static::getContainer()->set('bot403.client', new MockHttpClient(function (string $method, string $url, array $options) use ($answer) {
            $this->sentBody = $options['body'];

            return $answer;
        }, 'https://bot403.com'));

        $crawler = $client->request('GET', '/contact');
        $form = $crawler->selectButton('Send')->form([
            'contact[email]' => '[email protected]',
            'contact[message]' => 'Hi',
        ]);
        $client->request('POST', '/contact', $form->getPhpValues() + $extra);

        return $client;
    }

    public function testAVerifiedFormGoesThrough(): void
    {
        $this->send(new JsonMockResponse(['ok' => true, 'site' => 'pk_live_test']));

        $this->assertResponseRedirects('/thanks');
        parse_str($this->sentBody, $sent);
        $this->assertSame(['_bot403' => 'token'], $sent, 'only top-level fields go to Bot403');
    }

    public function testAFailedTokenIsRefused(): void
    {
        $this->send(new JsonMockResponse(['ok' => false, 'site' => 'pk_live_test', 'reason' => 'invalid']), []);

        $this->assertResponseStatusCodeSame(422);
        $this->assertSelectorTextContains('form', 'Send the form again.');
    }
}
Terminal
php bin/phpunit
# OK (2 tests, 6 assertions)

Then run symfony serve or php -S localhost:8000 -t public, and open http://localhost:8000/contact. Send the form. The browser goes to /thanks, and the site in your dashboard shows one check. If you get a failure that you do not expect, read the troubleshooting page. It lists every reason and its fix. For Laravel, read Stop form spam in Laravel. All guides are in the guides index.

Stop spam, not customers.

The CAPTCHA your visitors never see.

Get started free