← All posts

PHP: building a secure contact form from scratch (validation, CSRF, spam, SMTP)

Contact form full of spam, not delivering, or wide open? The complete code for a clean PHP form: server-side validation, CSRF token, honeypot, submission limits, SMTP delivery and a redirect after posting.

PHP: building a secure contact form from scratch (validation, CSRF, spam, SMTP)

Key points

  • All validation happens on the server: HTML attributes like required and type=”email” protect nothing.
  • A CSRF token, a honeypot, a minimum fill time and a per-IP limit stop most spam without forcing a captcha on anyone.
  • The email goes out over SMTP from an address on your own domain, with the visitor as Reply-To, followed by a redirect (Post/Redirect/Get).

The contact form is often the first piece of PHP people write, and one of the most copy-pasted. On sites we take over for maintenance, we regularly find forms that let through dozens of spam messages a day, whose messages never arrive because the visitor’s address is used as the sender, or that allow header injection so anyone can send email through the server. Here’s a complete framework-free PHP contact form, the way we’d write it for a simple site, with each safeguard explained so you can adapt it rather than paste it blindly.

The HTML form: CSRF token and honeypot

Besides the visible fields, the form creates a random CSRF token stored in the session and placed in a hidden field, records when the form was displayed so we can catch submissions that come back too fast, and includes a honeypot: a field visitors never see, but which bots fill in without thinking.

<?php
// contact-form.php
session_start();
$_SESSION['csrf'] ??= bin2hex(random_bytes(32));
$_SESSION['form_started'] = time();
?>
<form method="post" action="/contact.php">
  <input type="hidden" name="csrf" value="<?= htmlspecialchars($_SESSION['csrf']) ?>">

  <label for="name">Name</label>
  <input id="name" name="name" required maxlength="100" autocomplete="name">

  <label for="email">E-mail</label>
  <input id="email" name="email" type="email" required maxlength="190" autocomplete="email">

  <label for="message">Message</label>
  <textarea id="message" name="message" required maxlength="5000"></textarea>

  <!-- Honeypot, hidden with CSS : .hp { position: absolute; left: -9999px; } -->
  <div class="hp" aria-hidden="true">
    <label for="site">Leave this field empty</label>
    <input id="site" name="site" tabindex="-1" autocomplete="off">
  </div>

  <button type="submit">Send</button>
</form>

The honeypot is pushed off-screen with CSS rather than using type="hidden", which bots know to skip. tabindex="-1" keeps keyboard users out of it, aria-hidden hides it from screen readers, and the explicit label covers the rare human who stumbles on it.

To show errors and keep what the visitor typed (the processing script stores both in the session), run every value through htmlspecialchars().

required, maxlength and type="email" make life easier for the visitor but protect nothing: a bot posts whatever it likes straight to the script.

Server-side processing: CSRF, spam and validation

The script runs its checks cheapest first and stops as soon as one fails.

<?php
// contact.php: processing
session_start();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit;
}

function field(string $key): string
{
    $v = $_POST[$key] ?? '';
    return is_string($v) ? trim($v) : '';   // an array sent by hand becomes ''
}

// 1. CSRF token
if (!hash_equals($_SESSION['csrf'] ?? '', field('csrf'))) {
    http_response_code(400);
    exit('Your session has expired, please reload the page and send the form again.');
}

// 2. Anti-spam: honeypot filled in, or form sent in under 3 seconds
if (field('site') !== '' || time() - ($_SESSION['form_started'] ?? 0) < 3) {
    header('Location: /thank-you/', true, 303);   // tell the bot nothing
    exit;
}

// 3. At most 5 submissions per hour per IP address (APCu extension)
if (function_exists('apcu_inc') && apcu_inc('contact_' . $_SERVER['REMOTE_ADDR'], 1, $ok, 3600) > 5) {
    http_response_code(429);
    exit('Too many messages sent, please try again later.');
}

// 4. Validation
$name    = field('name');
$email   = field('email');
$message = field('message');
$errors  = [];

if ($name === '' || mb_strlen($name) > 100 || preg_match('/[rn]/', $name)) {
    $errors['name'] = 'Please enter your name (100 characters max).';
}
if (strlen($email) > 190 || filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
    $errors['email'] = "This email address doesn't look valid.";
}
if (mb_strlen($message) < 10 || mb_strlen($message) > 5000) {
    $errors['message'] = 'Your message must be between 10 and 5000 characters.';
}
if ($errors) {
    $_SESSION['errors'] = $errors;
    $_SESSION['old']    = compact('name', 'email', 'message');
    header('Location: /contact-us/', true, 303);
    exit;
}

What’s worth spelling out:

  • The field() helper guarantees we always handle a string. Without it, a bot posting name[]=x turns the value into an array, and trim() throws a fatal error on PHP 8.
  • hash_equals() compares tokens in constant time. An expired session makes the check fail; that’s the most common case for real visitors who leave a tab open for hours, hence a clear message rather than a blank page.
  • Line breaks are rejected in the name, because the name ends up in an email header (more below).

On most of the business websites we look after, the honeypot, the minimum fill time and the per-IP limit together get rid of the bulk of automated spam. Behind a proxy or CDN, check that REMOTE_ADDR really holds the visitor’s address, or everyone shares one limit.

Sending the email without header injection or the spam folder

This is the part most often done wrong, usually in one of two ways.

Using the visitor’s address as the sender. Your server isn’t allowed to send on behalf of gmail.com or a customer’s domain, so providers that check SPF, DKIM and DMARC reject the message or file it as spam. The sender must be an address on your domain; the visitor’s goes in Reply-To.

Putting visitor input into headers unchecked. With a line break in the name or address, an attacker adds headers of their own, such as a Bcc: to thousands of recipients, and uses your server as a spam relay. That’s the main risk with a carelessly used mail().

The most reliable approach is authenticated SMTP through a proven library such as PHPMailer, using the company’s mail server or a transactional email service with a properly configured domain:

<?php
// rest of contact.php: send over SMTP with PHPMailer (composer require phpmailer/phpmailer)
use PHPMailerPHPMailerPHPMailer;

require __DIR__ . '/vendor/autoload.php';

$mail = new PHPMailer(true);
try {
    $mail->isSMTP();
    $mail->Host       = getenv('SMTP_HOST');
    $mail->SMTPAuth   = true;
    $mail->Username   = getenv('SMTP_USER');
    $mail->Password   = getenv('SMTP_PASS');
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = 587;
    $mail->CharSet    = 'UTF-8';

    $mail->setFrom('website-form@example.com', 'Website form');   // ALWAYS your own domain
    $mail->addAddress('hello@example.com');
    $mail->addReplyTo($email, $name);                                 // Reply goes to the visitor
    $mail->Subject = 'Message from ' . $name;
    $mail->Body    = "Name: $namenEmail: $emailnn$message";      // plain text
    $mail->send();
} catch (Exception $ex) {
    error_log('Contact form: ' . $mail->ErrorInfo);
    exit("Your message couldn't be sent. Please email hello@example.com.");
}

unset($_SESSION['csrf']);                 // one token per submission
header('Location: /thank-you/', true, 303);   // Post/Redirect/Get
exit;

PHPMailer validates addresses and cleans headers, which closes the door on injection even if one of your own checks slips.

After sending: redirect, and what to test before launch

After a successful send, the script redirects to a thank-you page with a 303. That’s the Post/Redirect/Get pattern: if the visitor refreshes, the browser reloads the thank-you page instead of resubmitting, and you don’t get the message twice. A dedicated URL also makes conversions easy to track.

Before going live, test at least:

  • a normal submission: it reaches the inbox and Reply goes to the visitor;
  • an empty field, an invalid address, an over-long message: the error shows;
  • the honeypot filled in through dev tools: silent redirect, no email;
  • a name containing a <script> tag: shown as text, never executed.

In WordPress the logic is the same with the CMS’s own tools: wp_nonce_field() and wp_verify_nonce() for the token, the sanitize_* functions for input, and wp_mail() configured for SMTP.

FAQ

Do I still need a captcha?

Not necessarily. Start with the honeypot, the time check and the per-IP limit, then watch what gets through. A verification service becomes worthwhile if hand-typed messages or a smarter bot start getting past those filters.

Why do my form emails land in spam?

Usually because the sender is the visitor’s address, or a domain whose SPF and DKIM records don’t authorise your server. Send from an address on your domain through an authorised SMTP server, and put the visitor in Reply-To.

Is your contact form drowning in spam, or are enquiries going missing? We audit and secure the forms on your site and set up reliable email delivery.

Share LinkedIn Facebook X WhatsApp
</>

webtestudio

Web agency: custom WordPress sites, premium themes and SaaS software.

Discuss your project →