PHP

Building a contact form in PHP that is actually safe

Avi, the Avenux Techspire mascot, illustrating: Building a contact form in PHP that is actually safe

The contact form is usually the first “real” thing students build in PHP. It is also where a lot of bad habits start. Most tutorials take the POST data, drop it straight into mail(), and call it done. That form will work, but it will also get flooded with spam and can be abused in ways you did not expect.

Let us build one properly. Not complicated, just careful.

What can go wrong with a basic form

  • Cross-site request forgery (CSRF): another website can submit your form on behalf of a visitor.
  • Header injection: if user input ends up in email headers, an attacker can add extra recipients and use your server to send spam.
  • Cross-site scripting (XSS): if you print the submitted values back on the page without escaping, someone can inject JavaScript.
  • Bots: automated scripts will find your form within days and fill your inbox.

We will handle each of these.

Step 1: the form with a CSRF token

A CSRF token is a random value stored in the user’s session and also placed in a hidden field. When the form comes back, we check both match. A different website cannot read the token, so it cannot fake a valid submission.

<?php
session_start();
if (empty($_SESSION['csrf'])) {
    $_SESSION['csrf'] = bin2hex(random_bytes(32));
}
function e(string $value): string {
    return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
?>
<form method="post" action="contact.php">
  <input type="hidden" name="csrf" value="<?= e($_SESSION['csrf']) ?>">
  <input type="text" name="name" required maxlength="100">
  <input type="email" name="email" required maxlength="150">
  <textarea name="message" required maxlength="3000"></textarea>
  <!-- honeypot: real users never see or fill this -->
  <input type="text" name="website" class="hp" tabindex="-1" autocomplete="off">
  <button type="submit">Send</button>
</form>

Notice the small e() helper. Every time we print anything that came from a user, we pass it through htmlspecialchars(). Make that a habit everywhere, not only in this form.

The field called website is a honeypot. Hide it with CSS. Humans will leave it empty, simple bots fill in every field they see.

Step 2: validate on the server

The required and maxlength attributes in HTML are nice for users, but anyone can bypass them. The server must check everything again.

<?php
session_start();

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

$token = $_POST['csrf'] ?? '';
if (!hash_equals($_SESSION['csrf'] ?? '', $token)) {
    http_response_code(400);
    exit('Invalid request. Please reload the page and try again.');
}

if (!empty($_POST['website'])) {
    exit; // honeypot filled, quietly ignore
}

$name    = trim($_POST['name'] ?? '');
$email   = trim($_POST['email'] ?? '');
$message = trim($_POST['message'] ?? '');
$errors  = [];

if ($name === '' || mb_strlen($name) > 100) {
    $errors[] = 'Please enter your name.';
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $errors[] = 'Please enter a valid email address.';
}
if ($message === '' || mb_strlen($message) > 3000) {
    $errors[] = 'Please write a message under 3000 characters.';
}

We use hash_equals() to compare the tokens because it takes the same time whether the strings match early or late, which avoids timing tricks. filter_var() with FILTER_VALIDATE_EMAIL does a sensible check on the address format.

Step 3: send the email without header injection

Header injection happens when a value containing a line break goes into a header like Reply-To. A line break lets the attacker start a brand new header, such as Bcc. The email validation above already rejects line breaks in the email, but strip them from the name too, because people often put the name into headers.

<?php
if (!$errors) {
    $safeName = str_replace(["r", "n"], '', $name);
    $to       = 'hello@example.com';
    $subject  = 'New enquiry from ' . $safeName;
    $body     = "Name: $safeNamenEmail: $emailnn$message";
    $headers  = [
        'From'     => 'website@example.com',
        'Reply-To' => $email,
    ];

    mail($to, $subject, $body, $headers);
    unset($_SESSION['csrf']); // one token per submission
    header('Location: thank-you.php');
    exit;
}

Two important points here. First, the From address is your own domain, never the visitor’s address. Mail servers will reject or spam-folder messages that pretend to come from Gmail when they were sent from your server. Put the visitor’s address in Reply-To instead. Second, after sending we redirect to a thank you page. This is called Post/Redirect/Get, and it stops the form from being resent when the user refreshes.

On many hosts, mail() is unreliable. For anything serious, use a library like PHPMailer or Symfony Mailer with proper SMTP credentials. They also handle header encoding for you, which removes a whole class of mistakes.

Step 4: show errors safely

If validation fails, show the form again with the user’s values filled in so they do not have to retype everything. Just remember to escape them.

<?php foreach ($errors as $error): ?>
  <p class="error"><?= e($error) ?></p>
<?php endforeach; ?>
<input type="text" name="name" value="<?= e($name) ?>">

A few extra layers

  • Rate limiting: store a timestamp in the session and refuse a second submission within, say, thirty seconds.
  • CAPTCHA: if spam still gets through, add something like Cloudflare Turnstile or reCAPTCHA. Start with the honeypot though, it is free and invisible.
  • HTTPS: your form should only ever be served over HTTPS, otherwise the data travels in plain text.
  • Database storage: if you also store enquiries in a database, use PDO prepared statements, never string concatenation.

None of this is advanced. It is maybe forty extra lines compared to the unsafe version. But it is the difference between a form you can put on a client’s website and one you will regret. Build it this way once, keep it as your own template, and reuse it on every project.