Thuta Learning
PHP
ProjectsProgrammingBeginner

Contact Form Project

PHPLesson 3345 min

What you'll walk away with

  • Split a form handler into validate(), handle() and a store class instead of one tangled script
  • Test a handler with scripted $_POST-style arrays covering valid, empty, duplicate, spam and malformed input
  • Reject forged and bot submissions with a CSRF token comparison and a honeypot field
  • Escape output for HTML at the moment it is printed, not when it is stored

Explain it simply

Explain it simply

A contact form looks like one feature but is really a small pipeline: the visitor types, PHP checks the data, the database stores it, and the page shows a result. If you build each stage as its own small function, you can test the whole thing without opening a browser. Hand the function an array shaped like $_POST and read what comes back.

In this project that function is handle(). The real page will later call handle($_POST, ...); here we call it with prepared arrays.

Problem → Why → Solution

The problem: one script that does everything

The first version of most contact forms is one script: it reads $_POST, pastes the values into an INSERT and prints "Thanks". It is quick, but it has at least five problems. A missing field raises an "Undefined array key" warning. Whatever the visitor types goes straight into the SQL, which allows injection. Whatever they type is echoed back as HTML, which allows XSS. Blank and nonsense messages get stored. And pressing refresh re-sends the form and stores it twice.

Worst of all, you can only test it by filling in the form by hand in a browser, again and again.

contact-v1.php
<?php
// Everything in one place: reading, saving and printing are tangled together.
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $conn->query("INSERT INTO contacts (name, email, message) VALUES (
        '{$_POST['name']}', '{$_POST['email']}', '{$_POST['message']}')");
    echo "Thanks, {$_POST['name']}!";
}

Why is it so hard to test?

Every stage is welded to the web request: it reads $_POST directly and prints directly. Because no stage can be called on its own, none of them can be tested quickly. Once the stages are separated, each one has a clear input and a clear output.

Core concept: a line of checkpoints

A submission passes through checkpoints in order. If any checkpoint rejects it, the handler stops there and skips the later stages. The handler never prints; it returns a status, so both the page and the tests can use that status.

1. The request adapter

handle(array $post, string $sessionToken, ContactStore $store) never touches a superglobal; it only receives arrays. Only the web page file touches $_POST, so a test can pass a plain array instead.

2. CSRF token and honeypot

The CSRF token proves that your site served this form to this visitor's session. Compare it with hash_equals(), which takes the same time wherever the two strings differ. A honeypot is an input hidden with CSS: people leave it empty while bots fill in everything. Ignore bots silently instead of telling them what failed.

3. Validation

validate() returns [clean values, errors]. It trims, checks the type with is_string (a request with name[]=x delivers an array), enforces required fields, measures length with mb_strlen and checks the email with filter_var. It collects all the errors so the visitor can fix everything at once.

4. Storage

ContactStore wraps PDO. UNIQUE (email, message) is the duplicate policy: even if two requests arrive at the same moment, the database accepts only one. The store catches SQLSTATE 23000 and returns false.

5. Output

Escape at the moment you print into HTML, not when you save. Storing the raw text keeps the data correct for CSV exports, emails and JSON. Call htmlspecialchars() at the HTML boundary only.

StatusCauseVisitor sees
savedAll checks passedA thank-you page
invalidValidation errorsThe form again with messages and old values
duplicateSame email + message already storedA friendly "already received"
forbiddenWrong or missing CSRF tokenA "form expired" message
ignoredHoneypot was filled inA normal-looking thank-you (the bot learns nothing)
Mental model: a checkpoint line
  1. The request arrives as an array
  2. Check the token and honeypot
  3. validate() returns clean + errors
  4. Store it, then return a status

The handler never prints. It only returns a status, so the page and the tests can both use it.

General pattern

php
<?php
function handleSubmission(array $input, Service $service): array
{
    // 1. confirm the request is allowed (token, honeypot)
    // 2. validate and clean the input
    // 3. if anything is wrong, return the errors
    // 4. store the clean data
    // 5. return a status the page can display
}

A handler function takes an input array and a dependency, performs the five stages in order and returns a status array.

A testable contact handler

This file contains ContactStore (PDO + UNIQUE), validate() and handle(). In the lower half a valid submission called $good is broken in one place at a time with array_replace(), which creates many kinds of request in a uniform way. It needs no browser, web server or stdin. The course's MySQL lessons use MySQL, but here PDO with SQLite means no MySQL server is needed.

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

final class ContactStore
{
    public function __construct(private PDO $pdo)
    {
        $this->pdo->exec('CREATE TABLE IF NOT EXISTS contacts (
            id INTEGER PRIMARY KEY,
            name TEXT NOT NULL,
            email TEXT NOT NULL,
            message TEXT NOT NULL,
            UNIQUE (email, message)
        )');
    }

    /** Returns false when the same email + message is already stored. */
    public function save(array $clean): bool
    {
        $stmt = $this->pdo->prepare(
            'INSERT INTO contacts (name, email, message) VALUES (:name, :email, :message)'
        );
        try {
            $stmt->execute($clean);
            return true;
        } catch (PDOException $e) {
            if ($e->getCode() === '23000') { // integrity constraint violation
                return false;
            }
            throw $e;
        }
    }

    public function all(): array
    {
        $rows = $this->pdo->query('SELECT name, email FROM contacts ORDER BY id');
        return $rows->fetchAll(PDO::FETCH_ASSOC);
    }
}

/** @return array{0: array<string, string>, 1: array<string, string>} [clean, errors] */
function validate(array $post): array
{
    $clean = [];
    foreach (['name', 'email', 'message'] as $field) {
        $value = $post[$field] ?? '';
        $clean[$field] = is_string($value) ? trim($value) : '';
    }

    $errors = [];
    if ($clean['name'] === '') {
        $errors['name'] = 'Name is required.';
    } elseif (mb_strlen($clean['name']) > 60) {
        $errors['name'] = 'Name must be 60 characters or fewer.';
    }
    if (filter_var($clean['email'], FILTER_VALIDATE_EMAIL) === false) {
        $errors['email'] = 'Enter a valid email address.';
    }
    if (mb_strlen($clean['message']) < 10) {
        $errors['message'] = 'Message must be at least 10 characters.';
    }
    return [$clean, $errors];
}

function handle(array $post, string $sessionToken, ContactStore $store): array
{
    $token = $post['csrf'] ?? '';
    if (!is_string($token) || !hash_equals($sessionToken, $token)) {
        return ['status' => 'forbidden', 'errors' => ['csrf' => 'Form expired, reload.']];
    }
    if (($post['website'] ?? '') !== '') { // honeypot field: only bots fill it in
        return ['status' => 'ignored', 'errors' => []];
    }

    [$clean, $errors] = validate($post);
    if ($errors !== []) {
        return ['status' => 'invalid', 'errors' => $errors];
    }
    if (!$store->save($clean)) {
        return ['status' => 'duplicate', 'errors' => ['message' => 'Already received.']];
    }
    return ['status' => 'saved', 'errors' => []];
}

$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$store = new ContactStore($pdo);

$token = 'token-from-session';
$good = [
    'csrf' => $token,
    'name' => 'Aung Aung',
    'email' => 'aung@example.com',
    'message' => 'I would like a quote for a small website.',
];

$submissions = [
    'valid'        => array_replace($good, ['name' => '  Aung Aung ']),
    'duplicate'    => $good,
    'empty form'   => ['csrf' => $token],
    'bad email'    => array_replace($good, ['email' => 'aung@example']),
    'short text'   => array_replace($good, ['message' => 'Hi']),
    'bot'          => $good + ['website' => 'http://spam.example'],
    'wrong token'  => array_replace($good, ['csrf' => 'guess']),
    'array field'  => array_replace($good, ['name' => ['x']]),
    'html in name' => array_replace($good, [
        'name' => 'Su <b>Su</b>',
        'email' => 'su@example.com',
    ]),
    'Myanmar name' => array_replace($good, [
        'name' => 'မောင်မောင်',
        'email' => 'maung@example.com',
    ]),
];

foreach ($submissions as $label => $post) {
    $result = handle($post, $token, $store);
    echo str_pad($label, 13) . $result['status'];
    if ($result['errors'] !== []) {
        echo ' -> ' . implode(' | ', $result['errors']);
    }
    echo "\n";
}

echo "\nStored contacts (escaped for HTML output):\n";
foreach ($store->all() as $row) {
    echo '  ' . htmlspecialchars($row['name']) . ' <' . $row['email'] . ">\n";
}

Code breakdown

  1. Duplicates are a database ruleUNIQUE (email, message)

    If you SELECT first and INSERT afterwards, two simultaneous requests can both see "not stored yet" and both insert. UNIQUE lets the database itself guarantee it.

  2. Portable duplicate detectionif ($e->getCode() === '23000') { // integrity constraint violation

    SQLSTATE 23000 is the standard code for any constraint violation, so it works on MySQL too. Other errors are rethrown with throw $e instead of being hidden.

  3. Never trust the type$clean[$field] = is_string($value) ? trim($value) : '';

    A request containing name[]=x makes $post['name'] an array. The is_string check is why the "array field" line yields "Name is required." instead of a warning.

  4. Characters, not bytesmb_strlen($clean['name']) > 60

    strlen() counts bytes and mb_strlen() counts characters. The Myanmar name "မောင်မောင်" is 30 bytes but only 10 characters, so the length limit stays fair.

  5. Compare tokens safely!hash_equals($sessionToken, $token)

    hash_equals() takes the known token first and resists timing attacks. A plain === would also work, but hash_equals is the recommended way to compare secrets.

  6. Return a status, never printreturn ['status' => 'invalid', 'errors' => $errors];

    The handler returns the status and error texts as data only. That is what lets the foreach loop at the bottom format and print every outcome itself.

  7. Escape only when printinghtmlspecialchars($row['name'])

    The database holds the raw text Su <b>Su</b>, and the < and > characters are converted to their escaped form only when printed for HTML. You can see the result in the last lines of the output.

You should see
valid        saved
duplicate    duplicate -> Already received.
empty form   invalid -> Name is required. | Enter a valid email address. | Message must be at least 10 characters.
bad email    invalid -> Enter a valid email address.
short text   invalid -> Message must be at least 10 characters.
bot          ignored
wrong token  forbidden -> Form expired, reload.
array field  invalid -> Name is required.
html in name saved
Myanmar name saved

Stored contacts (escaped for HTML output):
  Aung Aung <aung@example.com>
  Su &lt;b&gt;Su&lt;/b&gt; <su@example.com>
  မောင်မောင် <maung@example.com>

Reading the output line by line

  • valid: the spaces around the name are trimmed and the first row is stored.
  • duplicate: email and message repeat, so UNIQUE fires and save() returns false.
  • empty form: the errors of all three fields are collected, not just the first one.
  • bot: the honeypot was filled in, so the result is ignored with no error text at all.
  • wrong token: forbidden before validation even starts, so a request with a bad token causes no further work.
  • html in name and Myanmar name: both are stored fine. Tags are not rejected; they are escaped at output.

Rendering the form again

When validation fails, the visitor's input must be put back into the form, otherwise they have to retype a long message. Their text now lands inside HTML, so it goes through e(). Notice that the textarea value sits between the tags, not in a value attribute. Since PHP 8.1 the default flags of htmlspecialchars already include ENT_QUOTES, but writing the flags yourself is clearer.

render-form.php
<?php
function e(string $text): string
{
    return htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function renderForm(array $old, array $errors): string
{
    $html = "<form method=\"post\">\n";
    foreach (['name', 'email'] as $field) {
        $value = e($old[$field] ?? '');
        $html .= "  <input name=\"$field\" value=\"$value\">\n";
        if (isset($errors[$field])) {
            $html .= '  <p class="error">' . e($errors[$field]) . "</p>\n";
        }
    }
    $html .= '  <textarea name="message">' . e($old['message'] ?? '') . "</textarea>\n";
    return $html . '</form>';
}

$old = [
    'name' => 'Su "the <b>boss</b>"',
    'email' => 'su@example',
    'message' => 'Is 5 < 7 & 7 > 5?',
];
$errors = ['email' => 'Enter a valid email address.'];

echo renderForm($old, $errors) . "\n";
text
<form method="post">
  <input name="name" value="Su &quot;the &lt;b&gt;boss&lt;/b&gt;&quot;">
  <input name="email" value="su@example">
  <p class="error">Enter a valid email address.</p>
  <textarea name="message">Is 5 &lt; 7 &amp; 7 &gt; 5?</textarea>
</form>

Quotes, < and & in the typed text can no longer break out of the attribute or the tag; they are displayed as plain characters. That is what prevents XSS.

Wiring handle() to a real page

The real page runs on a web server, so it is not executed in this lesson. It only passes the session token and $_POST to handle(). On success, redirect to a thank-you page (Post/Redirect/Get), so that pressing refresh cannot re-send the form and store it twice.

contact.php
<?php
// contact.php: runs on a web server, so it is not executed in this lesson.
declare(strict_types=1);
session_start();

if (empty($_SESSION['csrf'])) {
    $_SESSION['csrf'] = bin2hex(random_bytes(32)); // new token for this visitor
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $result = handle($_POST, $_SESSION['csrf'], $store);

    if ($result['status'] === 'saved') {
        header('Location: /thanks.php'); // Post/Redirect/Get: a refresh cannot re-submit
        exit;
    }
    // otherwise render the form again with $result['errors'] and the old values
}

In real projects

In real projects

Contact forms, newsletter signups and support-ticket forms all share this shape: check the token, validate, store, return a status. In production you add rate limiting (a cap on submissions per IP per minute), CAPTCHA and notifications that email your staff. Send the email after the commit, so you never email about a message that was not saved. This is why keeping handle() separate pays off: the page file may change while the tested core stays the same.

Never show a PDOException message to the visitor, because it can leak table names. Write it to a log and show the visitor "please try again later". Because messages contain personal data, decide in advance how long you keep them and what you do when someone asks you to delete theirs.

Common mistakes

Common mistakes

Escaping on input instead of output

If you escape before saving, the database holds already-escaped text, and the entity codes show up in CSV exports and emails. Escape twice and the escaped text is converted again, which gives double-escaped output. Store the original and escape only when printing HTML.

Trusting the shape of $_POST

Do not assume $_POST['name'] is always a string. name[]=x delivers an array, and the field may be missing entirely. Use ?? '' and is_string() so that "Undefined array key" and "Array to string conversion" warnings never appear.

Checking duplicates with SELECT then INSERT

When two requests arrive together, both SELECTs see "not stored yet" and both INSERTs run. Keep a UNIQUE constraint and catch its error. A SELECT check may still be added, but only for a friendlier message.

Putting a textarea value in a value attribute

An <input> takes its value from value="...", but a <textarea> keeps its value between the opening and closing tags. Put it in a value attribute and the browser ignores it, so the visitor's message disappears.

Mini challenge

Write a newsletter signup handler

Write subscribe(array $post, PDO $pdo): string. It takes a visitor's email and name and, when they are valid, stores them in the subscribers table. The consent checkbox must be the string "1". Treat emails that differ only in letter case as duplicates. No browser is needed; test it with prepared arrays.

  • Return "invalid: fields must be text" when email or name is not a string
  • Trim both, lowercase the email, and use "friend" when the name is empty
  • Check the email with filter_var ("invalid: email") and the consent value ("invalid: consent is required")
  • Use a prepared INSERT; SQLSTATE 23000 gives "duplicate: already subscribed" and success gives "subscribed"
challenge.php
<?php
declare(strict_types=1);

// $pdo already has: subscribers(id, email TEXT UNIQUE, name TEXT)

function subscribe(array $post, PDO $pdo): string
{
    // TODO: email and name must both be strings
    // TODO: trim them, lowercase the email, default the name to "friend"
    // TODO: validate the email, then the consent value
    // TODO: INSERT with a prepared statement and translate SQLSTATE 23000
    // TODO: return "subscribed" on success
}

Expected: "Su@Example.com " is subscribed, the same address in another case is a duplicate, a missing name is subscribed as "friend", and no consent, a bad email, an array email and an empty array are invalid. Two rows end up stored.

Show hint

The order of the checks matters: an empty array [] should reach the email check and give "invalid: email". Apply strtolower(trim($email)) before calling filter_var.

Show solution
challenge.php
<?php
declare(strict_types=1);

$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('CREATE TABLE subscribers (
    id INTEGER PRIMARY KEY,
    email TEXT NOT NULL UNIQUE,
    name TEXT NOT NULL
)');

function subscribe(array $post, PDO $pdo): string
{
    $email = $post['email'] ?? '';
    $name = $post['name'] ?? '';
    if (!is_string($email) || !is_string($name)) {
        return 'invalid: fields must be text';
    }

    $email = strtolower(trim($email));
    $name = trim($name);

    if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
        return 'invalid: email';
    }
    if (($post['consent'] ?? '') !== '1') {
        return 'invalid: consent is required';
    }

    try {
        $stmt = $pdo->prepare(
            'INSERT INTO subscribers (email, name) VALUES (:email, :name)'
        );
        $stmt->execute(['email' => $email, 'name' => $name === '' ? 'friend' : $name]);
    } catch (PDOException $e) {
        if ($e->getCode() === '23000') {
            return 'duplicate: already subscribed';
        }
        throw $e;
    }
    return 'subscribed';
}

$tests = [
    'new subscriber'   => [
        'email' => 'Su@Example.com ', 'name' => 'Su', 'consent' => '1',
    ],
    'same, other case' => ['email' => 'su@example.com', 'name' => 'Su', 'consent' => '1'],
    'no name'          => ['email' => 'mya@example.com', 'consent' => '1'],
    'no consent'       => ['email' => 'kyaw@example.com', 'name' => 'Kyaw'],
    'bad email'        => ['email' => 'kyaw@', 'name' => 'Kyaw', 'consent' => '1'],
    'array email'      => ['email' => ['a@b.com'], 'consent' => '1'],
    'empty'            => [],
];

foreach ($tests as $label => $post) {
    echo str_pad($label, 17) . subscribe($post, $pdo) . "\n";
}

$rows = $pdo->query('SELECT email, name FROM subscribers ORDER BY id');
foreach ($rows as $row) {
    echo "stored: {$row['email']} ({$row['name']})\n";
}

Quick quiz 1 / 3

What error does validate() report for $post = ['name' => ' ', 'email' => 'a@b.co', 'message' => 'A long enough message']?

Quick quiz 2 / 3

Two visitors submit the same email and message at the same instant. Which design guarantees only one row is stored?

Quick quiz 3 / 3

When should the visitor's name go through htmlspecialchars()?

What to remember

  • A form handler that takes an input array and returns a status can be tested without a browser
  • Compare the CSRF token with hash_equals, ignore the honeypot silently and check types with is_string
  • Guard duplicates with a UNIQUE constraint and catch SQLSTATE 23000
  • Store the original data and escape only when printing into HTML

PHP Language Reference — PHP Documentation Group

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Contact Form Project | Thuta Learning