Stop form spam in a PHP contact form

Updated

This guide adds Bot403 to a contact form in one plain PHP file, with no framework and no Composer. The browser solves a small proof of work. Then contact.php checks the token with one curl call before it sends the email. 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 needs PHP with the curl extension, and no Composer package. Run php -m and look for curl in the list, or ask your host. On 12 November 2026, the file on this page ran on PHP 8.4.25 and PHP 8.5.12 (official Docker images), against a local stand-in for the verify API that gives the documented answers. A good token went through and the email was written. A reused token, a filled honeypot and a form with no token were refused. A 402 quota answer and an API that did not answer let the form through. A wrong secret key refused every form and logged the reason.

Before you start

Sign in. Create a site. Copy its public key (pk_) and its secret key (sk_). The secret key must stay on the server, never in a page or in Git.

On a server where you set the environment, set BOT403_SECRET_KEY:

Terminal
export BOT403_SECRET_KEY=sk_live_YOUR_SECRET_KEY

On shared hosting with Apache, you often can't set the environment. Put the key in the .htaccess file of the folder that holds contact.php. PHP then finds it in $_SERVER, and the file below reads it from there first:

.htaccess
SetEnv BOT403_SECRET_KEY sk_live_YOUR_SECRET_KEY

Apache does not serve .htaccess files to visitors by default. If your host runs nginx, ask the host how to set an environment variable for PHP.

1. The file

One file shows the form, checks it and sends the email. Put it in your site as contact.php. Change MAIL_TO to your address, and MAIL_FROM to an address on your own domain.

contact.php
<?php
declare(strict_types=1);

// Where the messages go. MAIL_FROM must be an address on your own domain.
const MAIL_TO = '[email protected]';
const MAIL_FROM = 'Website <[email protected]>';

/** Posts the whole form to Bot403. Returns true when the form may go through. */
function bot403_check(array $form): bool
{
    $secret = $_SERVER['BOT403_SECRET_KEY'] ?? getenv('BOT403_SECRET_KEY');
    // 1. Post the whole form. Bot403 reads the _bot403 field and the honeypot field.
    $ch = curl_init('https://bot403.com/api/v1/verify');
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query($form),
        CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . $secret, 'Accept: application/json'],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 3,
        CURLOPT_TIMEOUT => 5,
    ]);
    $body = curl_exec($ch);
    $result = is_string($body) ? json_decode($body, true) : null;
    if (!is_array($result) || !array_key_exists('ok', $result)) {
        // No answer, or not JSON: Bot403 is down. Let the form through.
        error_log('bot403: no answer, letting the form through: ' . (curl_error($ch) ?: 'HTTP ' . curl_getinfo($ch, CURLINFO_RESPONSE_CODE)));
        return true;
    }
    $reason = $result['reason'] ?? '';
    if (in_array($reason, ['unauthorized', 'rate_limited', 'too_large'], true)) {
        error_log("bot403: verify refused the call: $reason");
    }
    // 2. Refuse when ok is false, except for reason "quota".
    return $result['ok'] === true || $reason === 'quota';
}

$error = $email = $message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim((string) ($_POST['email'] ?? ''));
    $message = trim((string) ($_POST['message'] ?? ''));
    if (!bot403_check($_POST)) {
        $error = 'Send the form again.';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL) || $message === '') {
        $error = 'Enter your email address and a message.';
    } else {
        $headers = [
            'From' => MAIL_FROM,
            'Reply-To' => $email,
            'Content-Type' => 'text/plain; charset=utf-8',
        ];
        if (mail(MAIL_TO, 'Message from the contact form', $message, $headers)) {
            header('Location: /contact.php?sent=1', true, 303);
            exit;
        }
        error_log('contact: mail() failed');
        $error = 'The message could not be sent. Try again later.';
    }
    http_response_code(400);
}
$h = fn (string $s): string => htmlspecialchars($s, ENT_QUOTES);
?>
<!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>
<?php if (isset($_GET['sent'])): ?>
  <p>Thanks. Your message is on its way.</p>
<?php else: ?>
  <form method="POST" action="/contact.php">
    <label>Email <input name="email" type="email" value="<?= $h($email) ?>" required></label>
    <label>Message <textarea name="message" required><?= $h($message) ?></textarea></label>
    <button type="submit">Send</button>
<?php if ($error !== ''): ?>
    <p role="alert"><?= $h($error) ?></p>
<?php endif; ?>
  </form>
<?php endif; ?>
</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). contact.php posts all of $_POST to Bot403, so both fields are checked.

2. What the check does

bot403_check() sends the form fields to https://bot403.com/api/v1/verify with the secret key. It returns true in three cases:

  • The answer is ok: true. A browser solved the puzzle for this site.
  • The reason is quota. That happens only in a capped month, and the token is not used up. The form goes through, so a capped month does not lose real messages.
  • Bot403 does not answer within 5 seconds, or the answer is not JSON. The form goes through, and PHP logs a warning.

Every other answer refuses the form. The form shows "Send the form again." and keeps what the visitor typed.

curl has no time limit by default. The libcurl docs say CURLOPT_TIMEOUT defaults to 0, which means the call never times out. The file sets 3 seconds to connect and 5 seconds in total. In the test run, a stand-in API that waited 30 seconds got this result: the form went through after 5.0 seconds, and the log said:

Log
bot403: no answer, letting the form through: Operation timed out after 5005 milliseconds with 0 bytes received

The trap: mail() header injection

Never put a value from the form into the From header or the subject. A line break in a header value starts a new header. A value such as [email protected] followed by a line break and Bcc: … turns your form into a relay that sends their spam to other people, from your server.

contact.php puts only one value from the form into a header: the email address, in Reply-To. It checks the address first with filter_var($email, FILTER_VALIDATE_EMAIL), which refuses any value with a line break. In the test run, an email field with a line break and a Bcc: line was refused with "Enter your email address and a message.", and no email was written. The subject is fixed, and the message goes only in the body.

From is your own address for a second reason. Mail that claims to come from the visitor's domain fails that domain's SPF and DMARC checks, so it often lands in spam. With Reply-To, you can still answer the visitor with one click.

Bot403 does not replace this check. It stops scripts that send the form. It does not check what a person types.

Why the file posts all of $_POST

Post the whole form, not only the token. The honeypot field has a name you can change in the site settings of the dashboard, and Bot403 checks it only when it gets it. $_POST holds only the text fields, never the files, so an upload does not go to Bot403. In the test run, a multipart form with a file went through, and the stand-in API got only the text fields. The verify API refuses a body over 64 KB with HTTP 413, so keep text fields under that size.

When the secret key is wrong

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

Log
bot403: verify refused the call: unauthorized

Every form on the site fails until you fix the key, so look for this line in the PHP error log after you upload the file. The same log 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.

Forms sent with fetch

If you send the form with fetch, send it as FormData, so the token and the honeypot field go with it. PHP fills $_POST from a FormData body. A JSON body leaves $_POST empty, so the token never reaches Bot403 and every form is refused as invalid.

contact.js
const form = document.querySelector("form");
form.addEventListener("submit", async (event) => {
  event.preventDefault();
  // holds _bot403 and the honeypot field
  const res = await fetch(form.action, { method: "POST", body: new FormData(form) });
  if (res.ok) location.href = res.url;
});

The script listens to the submit event before your own code does. It waits for the token, puts it in the _bot403 field, and then submits again. So when your handler runs, the form already holds the token.

Test it

Run the file on your computer with PHP's built-in server:

Terminal
BOT403_SECRET_KEY=sk_live_YOUR_SECRET_KEY php -S localhost:8000

Then send a form without a token, the way a simple bot does. It must be refused:

Terminal
curl -s -o /dev/null -w '%{http_code}\n' -d '[email protected]' -d 'message=Hi' http://localhost:8000/contact.php
# 400

Open http://localhost:8000/contact.php in a browser and send the form. The page shows "Thanks. Your message is on its way.", and the site in your dashboard shows one check. If your computer has no mail server, mail() fails, and the page shows "The message could not be sent. Try again later." That still means the check passed. Upload the file to the host to test the email.

If you get a failure that you do not expect, read the troubleshooting page. It lists every reason and its fix. For a Laravel app, 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