Skip to content
Tutorials Center
My learning

Topics

Lesson 129 of 147 ยท Projects

Project: Contact Form with Validation

Build a secure PHP contact form in four stages - sticky escaped fields, server-side validation, CSRF tokens and a honeypot, then sending the message by email.

Almost every website has a contact form, and a surprising number of them are broken in some way. Some lose everything the visitor typed when one field is wrong. Some print the visitor's input back into the page without escaping it. Some can be abused to send spam to strangers through the site's own mail server. A good contact form is a compact exercise in doing every part of form handling properly.

In this project you'll build one in four stages, each a complete program. First you'll render the form with sticky values (fields that keep what the user typed) and safe escaping. Then you'll write the validation rules and error messages. Then you'll protect the form against forged submissions with a CSRF token and against bots with a honeypot field and a rate limit. Finally you'll put it all behind a request handler that sends the message through a mailer and shows a one-time success message. You'll use what you learned in Handling Forms, Form Validation, Sessions and Preventing CSRF.

Our editor runs PHP on the command line, with no browser, web server or mail server. The stages simulate form submissions with plain arrays shaped like $_POST, and a plain array stands in for $_SESSION. Stage 4 sends mail through a fake mailer that prints the message instead of delivering it. The section after stage 4 shows the real-server versions.

The plan

The form has four visible fields:

Field Rule
name required, 2 to 80 characters, no line breaks
email required, a valid email address, at most 254 characters
topic one of general, support or billing
message required, 10 to 2,000 characters

It also has two hidden fields that a human visitor never fills in: csrf_token and a honeypot called website.

The request flow follows the POST-redirect-GET pattern you used in the to-do list project:

  1. GET /contact shows an empty form.
  2. POST /contact validates the submission. If anything is wrong, the form is shown again with the user's values and an error message under each bad field. If everything is fine, the message is sent and the browser is redirected.
  3. The redirected GET /contact shows "Thanks, your message was sent." exactly once.

Stage 1: a sticky, escaped form

The rendering function takes two arrays: the current $values (empty on the first visit, the submitted values after a failed attempt) and the $errors, keyed by field name. It returns the form's HTML.

Escaping is the most important detail. Each value goes inside a value="..." attribute or a <textarea>, so e() calls htmlspecialchars with ENT_QUOTES, which converts both " and '. Without it, a name like Dana "DJ" Kim would end the attribute after Dana and turn the rest into extra attributes, and a malicious visitor could inject a script that way. The Preventing XSS lesson covers this in depth.

The template is a heredoc, which keeps the HTML readable. A heredoc can interpolate variables, and also calls of closures stored in variables, like {$value('name')}, but not plain function calls like {e($x)}. So renderForm first creates three small arrow functions: $value returns an escaped field value, $invalid adds the error attributes and $error adds the error message. Arrow functions capture $values and $errors from the surrounding function automatically.

For accessibility, each input has a <label>, and a field with an error gets aria-invalid="true" plus aria-describedby pointing at its message, so screen readers announce the problem together with the field.

PHP Stage 1: a sticky form with escaped values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The first form is empty. The second keeps everything the user typed: value="Dana &quot;DJ&quot; Kim", the Billing option marked selected, and the message inside the <textarea> with &lt;twice&gt; and &amp;. Only the email field is marked invalid, with its message right below it. (Our editor shows the HTML as text; a browser would render a form.)

Notice that field() checks is_string. A visitor can send email[]=x, and PHP then puts an array into $_POST['email']. Passing that array to htmlspecialchars under strict_types would throw a TypeError and show an error page. Treating a non-string as an empty string is the calm response.

Stage 2: validation

Validation turns raw input into either clean data or a list of errors. validateContact returns both: ['data' => [...], 'errors' => [...]]. The data contains trimmed values, and the errors array has at most one message per field, written for a human ("Please enter your name.", not "name: required").

The rules use the right tool for each field:

  • Lengths use mb_strlen, which counts characters rather than bytes, so Zoรซ is 3 characters. See Unicode and Multibyte Strings.
  • Line breaks in the name are rejected with preg_match('/[\r\n]/', ...). A name ends up in an email header in stage 4, and a newline there would let an attacker add headers of their own (more on that later). The Regular Expressions lesson explains the pattern syntax.
  • The email is checked with filter_var($email, FILTER_VALIDATE_EMAIL). It follows the address rules closely enough for real use: it rejects zoe@, two@@signs.com and also dana@example, because it requires a domain with a dot, which suits a public website. By default it also rejects non-ASCII characters before the @ (zoรซ@example.com); add the FILTER_FLAG_EMAIL_UNICODE flag if you want to accept them.
  • The topic must be a key of TOPICS. Never trust that a <select> can only send the options you listed; anyone can send any value.
PHP Stage 2: validating submissions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The valid submission comes back with the name trimmed to Zoรซ Laurent. The empty one gets an error for all four fields (an empty topic isn't in the list either). The header-injection attempt is stopped by the line-break rule, and the last submission shows both protections working: the array sent as name counts as empty, and a message of 2,002 characters is reported with its real length.

A few validation habits worth copying:

  • Validate the trimmed value, and keep it. The cleaned data is what you use from here on, so a message never starts with stray spaces.
  • One message per field. The elseif chains stop at the first problem. Showing "required" and "too short" together for an empty field would just be noise.
  • Say how to fix it. "Your message must be at least 10 characters long" is better than "Invalid message".
  • Client-side checks are only a convenience. You can add required, maxlength and type="email" to the HTML for instant feedback, but the server must check everything again, because a request can be sent without any browser at all.

Stage 3: CSRF tokens, a honeypot and a rate limit

The form now produces clean data, but two kinds of unwanted submissions can still get through.

Cross-site request forgery. Another website can contain a hidden form that posts to your /contact URL, and a visitor's browser will happily submit it, with the visitor's cookies attached. For a contact form, that lets an attacker send messages that look like they came through your site from your visitors. The defense is a CSRF token: a long random value stored in the visitor's session and copied into a hidden field of every form. A forged form on another site can't know the token, so its submissions are rejected. Preventing CSRF covers the attack and the SameSite cookie setting, which helps too.

The token is created with bin2hex(random_bytes(32)), which gives 64 hex characters from the operating system's secure random generator. It's compared with hash_equals, which takes the same time no matter where the strings first differ, so an attacker can't learn the token one character at a time by measuring response times. (Hashing, Encryption and Random Numbers explains why ordinary === isn't used for secrets.)

Spam bots. Bots fill in every field they find. A honeypot is an extra text field, hidden from humans with CSS, that real visitors leave empty. If it has a value, the submission is almost certainly a bot. To avoid tipping the bot off, the app pretends the message was sent and quietly drops it.

Finally, a simple rate limit stores the times of recent submissions in the session and refuses more than three in ten minutes. That stops a person from flooding your inbox by pressing Send repeatedly. (A determined attacker can start new sessions, so production sites also limit by IP address in a shared store such as Redis or the database.)

In this stage the session is a plain array passed by reference (array &$session), standing in for $_SESSION. Time is passed in as $now, so the demo can simulate submissions minutes apart without waiting.

PHP Stage 3: CSRF token, honeypot and rate limit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The token is 64 characters long and stays the same for the whole session, so a visitor can open the form in several tabs. The forged form, the wrong token and the array-instead-of-string trick are all rejected (the is_string check matters: hash_equals requires strings and would throw a TypeError for an array). The bot is "dropped silently". Messages 1 to 3 are accepted, message 4 hits the limit, and message 5, sent 11 minutes after the first, is accepted again because the first message has left the ten-minute window.

Order matters in checkSubmission. The CSRF check comes first because a forged request shouldn't be able to do anything, not even use up the visitor's rate limit. The honeypot comes before the rate limit for the same reason: a bot shouldn't affect what a real visitor in the same session is allowed to do.

Stage 4: the complete form with a mailer

The last stage combines everything into one handleRequest function, plus the part we haven't written yet: sending the email.

The code doesn't call a mail function directly. It depends on a small Mailer interface with one method, send(Email $email). The demo passes a FakeMailer that just remembers the messages, and a real site passes an implementation that talks to a mail server. This is dependency injection, covered in OOP Design Principles: the handler doesn't care how mail is delivered, so you can test it without sending anything.

The email itself is a readonly value object, Email, built only from validated data. Look closely at its headers:

  • From is always our own address, [email protected]. If you put the visitor's address in From, receiving servers would see an email "from gmail.com" sent by your server, and anti-spoofing checks (SPF, DKIM and DMARC) would likely reject it or mark it as spam.
  • Reply-To holds the visitor's address, so pressing Reply in your mail program answers the visitor.
  • The subject is built from the fixed topic label, not from free text. Combined with the no-line-breaks rule for the name, nothing a visitor types can create a new header line.

After a successful send, the handler stores a flash message in the session and redirects with 303 See Other. The next GET shows the message and removes it from the session, so a reload doesn't show it again. A failed validation answers 422 Unprocessable Content with the form, the errors and the sticky values. (Many sites answer such forms with 200; both work in browsers, but 422 tells tools and tests precisely what happened.)

PHP Stage 4: the full contact form flow

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Follow the output request by request. The first visit shows the form (the demo prints the token shortened to 8 characters plus ... to keep the output short; a real page includes all 64). The forged post gets 403 with a friendly message. The invalid post gets 422, lists two errors (email and message) and keeps the values, with the name escaped as Ana &lt;b&gt;Ruiz&lt;/b&gt;. The valid post answers 303 Location: /contact, the redirected page shows the thank-you message, and the reload shows a plain form again, because the flash message was removed when it was first displayed. At the end, the fake mailer has exactly one email, with our address in From and Ana's in Reply-To.

Two small but deliberate choices:

  • $session['csrf_token'] ??= ... uses the null coalescing assignment operator to create the token only once per session.
  • ['data' => $data, 'errors' => $errors] = validateContact($post); is keyed destructuring, which unpacks both parts of the result in one line.

Running it on a real server

On a real server, $_SESSION replaces the session array, and the request comes from the superglobals. The top of contact.php looks like this:

PHP
<?php

declare(strict_types=1);

session_start([
    'cookie_httponly' => true,
    'cookie_secure' => true,      // send the cookie over HTTPS only
    'cookie_samesite' => 'Lax',   // not sent with cross-site POSTs
]);

require __DIR__ . '/../src/contact.php';   // handleRequest(), validateContact(), ...

[$status, $headers, $body] = handleRequest(
    $_SERVER['REQUEST_METHOD'],
    $_POST,
    $_SESSION,
    new SmtpMailer(/* host, user, password from environment variables */),
);

http_response_code($status);
foreach ($headers as $name => $value) {
    header("$name: $value");
}
echo $body;

session_start() must run before any output, because it sends the session cookie as an HTTP header; see HTTP Headers and Redirects for the "headers already sent" error. Passing $_SESSION to a by-reference parameter works as you'd expect: the handler's changes land in the real session.

The honeypot field is hidden with CSS rather than type="hidden" (bots know to skip hidden inputs), and autocomplete="off" keeps password managers from filling it:

HTML
<div class="visually-hidden" aria-hidden="true">
  <label for="website">Leave this field empty</label>
  <input id="website" name="website" tabindex="-1" autocomplete="off">
</div>

Sending the email for real

PHP has a built-in mail() function. It hands the message to the server's local mail program (sendmail on Linux), so it only works if one is installed and configured:

PHP
$sent = mail(
    INBOX_ADDRESS,
    $email->subject,
    $email->body,
    [
        'From' => SITE_ADDRESS,
        'Reply-To' => $email->replyTo,
        'Content-Type' => 'text/plain; charset=UTF-8',
    ],
);
if (!$sent) {
    error_log('Contact form: mail() failed');
}

mail() gives you very little: no SMTP authentication, no useful error messages and no protection beyond what you validate yourself. Most projects use a library instead, installed with Composer. With Symfony Mailer, a SmtpMailer implementation of our interface could look like this:

PHP
use Symfony\Component\Mailer\Mailer as SymfonyMailer;
use Symfony\Component\Mailer\Transport;
use Symfony\Component\Mime\Email as MimeEmail;

final class SmtpMailer implements Mailer
{
    private SymfonyMailer $mailer;

    public function __construct(string $dsn)   // e.g. 'smtp://user:[email protected]:587'
    {
        $this->mailer = new SymfonyMailer(Transport::fromDsn($dsn));
    }

    public function send(Email $email): void
    {
        $this->mailer->send((new MimeEmail())
            ->from($email->from)
            ->to($email->to)
            ->replyTo($email->replyTo)
            ->subject($email->subject)
            ->text($email->body));
    }
}

The library encodes headers correctly, refuses line breaks in them, and throws an exception when the server rejects the message. Because the rest of the app only knows the Mailer interface, switching from FakeMailer to SmtpMailer is a one-line change. Keep the SMTP password in an environment variable, never in the code (see Deploying PHP Applications).

Never send an automatic copy of the message to the address the visitor typed in ("send me a copy"). Spammers love such forms: they enter a victim's address and an advertisement as the message, and your server delivers it. If you want to confirm receipt, do it only for logged-in users with verified addresses.

Ideas for extending the form

  • Store messages in a database as well as emailing them, using PDO, so nothing is lost if the mail server is down.
  • A character counter for the message, in JavaScript, while the server keeps enforcing the 2,000 limit.
  • An attachment field, validated as in File Uploads: size limit, finfo type check and a generated file name.
  • A minimum fill time. Store the time the form was shown in the session, and treat submissions faster than three seconds as bots.
  • Tests for validateContact and handleRequest, using the FakeMailer to assert what was sent; see Testing PHP Code.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the form escape values with ENT_QUOTES before placing them in value="..."?

    An unescaped double quote would close the attribute early, and the rest of the input could add new attributes or tags. ENT_QUOTES converts both " and ' to entities.
  2. 2. What does validateContact do with $_POST['name'] if a visitor sends name[]=Max?

    The is_string check in field() turns unexpected arrays into an empty string, so the form fails validation calmly instead of crashing.
  3. 3. Why is the CSRF token compared with hash_equals instead of ===?

    A normal comparison can stop at the first different character. hash_equals runs in constant time, which prevents timing attacks on secret values.
  4. 4. Which address does the email use in the From header, and why?

    Your server isn't allowed to send mail for the visitor's domain. Put your own address in From and the visitor's in Reply-To so replies still reach them.
  5. 5. In stage 3, why does a filled honeypot get a "success" response instead of an error?

    Telling a bot its submission was refused teaches its author to avoid the honeypot. Pretending to succeed and silently dropping the message gives nothing away.

Summary

  • Re-display a failed form with the user's values (sticky fields) and one clear message per field, escaped with htmlspecialchars(..., ENT_QUOTES).
  • Treat every field as an untrusted value that may be missing or an array; trim strings and validate the trimmed value.
  • Use mb_strlen for lengths, filter_var(..., FILTER_VALIDATE_EMAIL) for addresses, a whitelist for <select> values, and reject line breaks in anything that reaches an email header.
  • Protect forms with a session CSRF token from random_bytes, compared with hash_equals; add a honeypot and a rate limit against bots and floods.
  • Answer invalid submissions with the form (422) and successful ones with a 303 redirect plus a one-time flash message.
  • Send mail through an interface so you can test with a fake mailer; use your own address in From, the visitor's in Reply-To, and a library such as Symfony Mailer in production.

Next: Project: Mini Blog with PDO