Development
How to Build a PHP Contact Form That Resists Spam

A PHP contact form resists spam through several small controls: validate bounded input on the server, reject obvious automation, limit submissions using shared state, and separate message acceptance from email delivery. No single hidden field makes a public endpoint abuse-proof.
Start with the actual requirement. A contact form needs a reply address, a message, and enough context to route it. Every extra field creates validation and privacy work.
Validate the contact form before sending anything
The following PHP 8.1 example is the validation portion of an endpoint. It does not send mail or implement a distributed rate limiter. Treat it as a function called after request-size and request-method checks.
<?php
declare(strict_types=1);
/** Validate bounded contact fields and quietly classify a filled honeypot. */
function validateContact(array $input): array
{
foreach (['email', 'message', 'website'] as $field) {
if (isset($input[$field]) && !is_string($input[$field])) {
return ['errors' => ['form' => 'Invalid form input.']];
}
}
if (trim($input['website'] ?? '') !== '') {
return ['spam' => true];
}
$email = trim($input['email'] ?? '');
$message = trim($input['message'] ?? '');
$errors = [];
if (strlen($email) > 254 || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['email'] = 'Enter a valid reply address.';
}
if ($message === '' || strlen($message) > 10000) {
$errors['message'] = 'Enter a message up to 10,000 bytes.';
}
return ['errors' => $errors, 'email' => $email, 'message' => $message];
}
The byte limit is deliberate and independent of a visual character counter. PHP documents its email validation filter in filter validation. Validation does not establish that an address belongs to the sender.
Render validation messages and retained input with HTML escaping. Never place the submitted address directly into raw email headers. Use a mail library's address setter and keep your own verified domain in the From field; put the visitor's address in Reply-To only after validation.
Add a honeypot without trapping real visitors
A honeypot is an extra field that ordinary visitors should leave empty. Keep it outside the normal keyboard path and provide clear instructions for assistive technology if it remains exposed. Test autofill and password managers. A field named website may be filled legitimately by some tools, so measure false positives before treating it as decisive.
Return the same neutral response for an obvious bot submission. Do not reveal which trap fired. Also avoid sending a confirmation email to every unverified submitted address: that can turn the form into a tool for harassing other people.
Rate limit before expensive work
Use an atomic shared counter with an expiry, such as Redis, rather than a counter stored only in a browser session. Limit by several signals and set a global delivery budget. An attacker can rotate cookies; an IP-only limit can unfairly block an office sharing one connection.
Trust forwarding headers only from your configured proxy. Otherwise a caller can invent a new address on every request. Log the rejection reason with a request identifier, while avoiding full message bodies and unnecessary personal data.
A challenge can be an escalation for suspicious traffic, but it needs server-side verification, an accessible fallback, and monitoring. It does not replace bounded input or a mail budget.
Accept once and deliver reliably
After validation and abuse checks, store an accepted message with a unique submission identifier and queue delivery. A successful form response should mean your system accepted responsibility, not that the recipient definitely received an email.
Use a redirect after successful POST to avoid accidental browser refresh resubmission. For stronger duplicate protection, enforce a unique submission key in storage. Keep the queue worker retryable and alert on old undelivered messages.
Test malformed arrays, empty messages, oversized bodies, repeated submissions, a filled honeypot, transport failures, and shared-office traffic. Track accepted messages, rejected requests, delivery failures, and false positives separately.
For the surrounding application structure, see incremental PHP refactoring. Discuss your form workflow if delivery and abuse handling need to fit an existing system.