iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

PHP Form Complete

A complete contact-form handler — POST → validate → process → redirect → re-render with errors. Use this as a template for real apps.

The script

PHP — contact.php
<?php
$errors = [];
$old    = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 1. Grab + trim
    $name    = trim($_POST['name']    ?? '');
    $email   = trim($_POST['email']   ?? '');
    $message = trim($_POST['message'] ?? '');
    $old = compact('name', 'email', 'message');

    // 2. Validate
    if ($name === '')                                  $errors['name']    = 'Required';
    if (!filter_var($email, FILTER_VALIDATE_EMAIL))    $errors['email']   = 'Invalid email';
    if ($message === '')                               $errors['message'] = 'Required';
    elseif (mb_strlen($message) > 2000)                 $errors['message'] = 'Too long';

    // 3. On success, save + redirect
    if (empty($errors)) {
        save_message($name, $email, $message);
        header('Location: /thanks');
        exit;
    }
}
?>
<!DOCTYPE html>
<html>
<body>
<form method="post">
    <label>Name
        <input name="name" value="<?= htmlspecialchars($old['name'] ?? '') ?>">
    </label>
    <?php if (isset($errors['name'])): ?>
        <p class="err"><?= htmlspecialchars($errors['name']) ?></p>
    <?php endif; ?>

    <label>Email
        <input type="email" name="email" value="<?= htmlspecialchars($old['email'] ?? '') ?>">
    </label>
    <?php if (isset($errors['email'])): ?>
        <p class="err"><?= htmlspecialchars($errors['email']) ?></p>
    <?php endif; ?>

    <label>Message
        <textarea name="message"><?= htmlspecialchars($old['message'] ?? '') ?></textarea>
    </label>
    <?php if (isset($errors['message'])): ?>
        <p class="err"><?= htmlspecialchars($errors['message']) ?></p>
    <?php endif; ?>

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

Why this pattern

  • Single file shows the form and processes it — common in small apps.
  • POST → redirect → GET protects against refresh-resubmits.
  • $old repopulates the form after a failed validate.
  • htmlspecialchars everywhere = no XSS from your own form.
Tip: Once a project has more than two forms, lift validation rules into a class. Laravel's FormRequest, Symfony's Form, or your own DTO class — pick a pattern and stick to it.

Example

Example
<?php
// Real form handlers do: validate → sanitise → process → redirect.
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = htmlspecialchars(trim($_POST['name'] ?? ''), ENT_QUOTES);
    if ($name !== '') {
        // header('Location: /thanks'); exit;
        echo "Thanks, $name!";
    }
}
Try it Yourself »

Exercise

Redirect after a successful POST.

('Location: /thanks'); exit;

Test yourself

Q1. Pattern flow is…
Q2. Re-populating fields uses…
Q3. For multiple forms prefer…

Discussion

Loading…