Thuta Learning
PHP
IntermediateProgrammingBeginner

Handling Forms

PHPLesson 1835 min

What you'll walk away with

  • Structure a form request as render, submit, validate, act and redirect
  • Validate each field, collect errors by field name, and refill inputs with escaped values
  • Explain why a successful POST ends with a 303 redirect (PRG) and what a refresh does
  • Check a CSRF token with hash_equals() and handle fields browsers may not send, such as checkboxes

Explain it simply

Explain it simply

A form is the doorway through which visitors send information to your server. Contact forms, logins, orders and feedback forms all work the same way: HTML shows fields to fill in, and when the user presses submit the browser sends a POST request. PHP takes the data from $_POST, checks it, acts on it when it is valid, and explains the problem when it is not.

A good form handler does five jobs: show the form, receive the submission, check the fields, act if everything is valid, and then redirect. Each step solves a different problem, so this lesson walks through why each one is needed.

Problem → Why → Solution

The problem: three flaws in a first form handler

First form scripts tend to hit these flaws one after another. First, merely opening the page (a GET) reads $_POST["fname"] and prints Warning: Undefined array key "fname". Second, the action runs on every request without checking the method, so even a GET is treated as "already submitted". Third, the script shows the result page straight after a successful submit, so when the user refreshes, the browser asks whether to resend the form, and agreeing sends the message a second time.

On top of that, a mistyped email wipes everything else the user typed and returns an empty form, and echoing the text back without escaping opens the door to XSS.

naive-form.php
<?php
$name = $_POST["fname"];                        // Warning on the first (GET) visit
saveMessage($name);                             // runs on EVERY request, even a GET
echo "Thanks, " . $_POST["fname"];              // raw output, and a refresh resends

Why does this happen?

One form page has to handle two kinds of request: the GET that shows the form and the POST that receives data. If the script does not separate them, it warns when there is no POST and does the work when it should not. Browsers also prepare to resend a POST when the result page is refreshed, so without a redirect duplicates happen. The cure is the pattern of checking the method, validating, acting and only then redirecting (PRG).

Core concept: render, submit, validate, act, redirect

A form follows five steps in sequence, and your PHP code chooses the path from REQUEST_METHOD: a GET shows the form, a POST takes the receiving path. When you validate, check each field and collect the errors in one array keyed by field name, so each message can be shown beside the right input.

1. Render

On a GET request, output the HTML form. When there are errors, include the messages and refill the previous values, escaped.

2. Submit

When the user presses the button the browser sends a POST and PHP fills $_POST. The script selects this path with $_SERVER["REQUEST_METHOD"] === "POST".

3. Validate

Check every field for presence, type, length and format. Do not lean on the browser's required attribute; only the server-side check is a real check.

4. Act

Only when there are no errors do you do the real work, such as saving to a database or sending an email. With errors, go back to step 1 and show the form again with a 422 status.

5. Redirect

On success, send the browser to a GET page with header("Location: ...", true, 303) and exit. A refresh then repeats only that GET, so nothing is done twice. This is called Post/Redirect/Get (PRG).

Three facts about forms are worth knowing. First, an unchecked checkbox is not sent by the browser at all, so you test it with isset($_POST["terms"]). Second, HTML attributes such as required and type="email" exist for the user's convenience and cannot stop a forged request sent with curl. Third, using POST alone does not prevent CSRF, where another site tricks a user into submitting your form, so you pair a session-stored token with a hidden field and compare them with hash_equals().

Mental model: show, check, act, redirect
  1. GET: show the form
  2. POST: check every field on the server
  3. Errors: show form and typed values
  4. Valid: act, then 303 redirect

After success, redirect instead of rendering a page directly, so a refresh cannot create a duplicate.

General pattern

php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $errors = validate($_POST);          // collect messages keyed by field name

    if ($errors === []) {
        save($_POST);                    // act only when nothing is wrong
        header("Location: /thanks", true, 303);
        exit;                            // nothing may run after a redirect
    }
}
// show the form; print $errors and the old values, escaped

Check the method, validate, save only when there are no errors, then redirect with header() and exit. header() must be called before any output; calling it later gives "headers already sent". When there are errors you do not redirect; you show the form again.

Example: the three paths of a contact form handler

This example shows the PHP side of the HTML form below. The CLI has no web request and no usable header(), so handleContact() takes fixed arrays and returns an array describing the response it would send. That lets you try a GET, two bad POSTs and a good POST without a web server. In a real page you would send the returned status and location with http_response_code() and header().

contact.html
<form method="post" action="">
  <label for="name">Name</label>
  <input id="name" name="name" required>

  <label for="email">Email</label>
  <input id="email" name="email" type="email" required>

  <button type="submit">Send</button>
</form>
contact.php
<?php
function field(array $input, string $key): string
{
    $value = $input[$key] ?? "";
    return is_string($value) ? trim($value) : "";
}

function validateContact(array $input): array
{
    $errors = [];
    $name = field($input, "name");
    if ($name === "") {
        $errors["name"] = "Name is required.";
    } elseif (mb_strlen($name) > 40) {
        $errors["name"] = "Name must be 40 characters or fewer.";
    }
    if (filter_var(field($input, "email"), FILTER_VALIDATE_EMAIL) === false) {
        $errors["email"] = "Enter a valid email address.";
    }
    return $errors;
}

function handleContact(string $method, array $post): array
{
    if ($method !== "POST") {
        return ["status" => 200, "errors" => [], "old" => ["name" => ""]];
    }
    $errors = validateContact($post);
    if ($errors !== []) {
        $old = ["name" => field($post, "name")];
        return ["status" => 422, "errors" => $errors, "old" => $old];
    }
    // act here: save the message, send an email, then redirect
    return ["status" => 303, "location" => "/thanks"];
}

function describe(array $response): string
{
    if ($response["status"] === 303) {
        return "303 redirect to " . $response["location"];
    }
    $hasErrors = $response["errors"] !== [];
    $lines = [$response["status"] . ($hasErrors ? " form again" : " empty form")];
    foreach ($response["errors"] as $field => $message) {
        $lines[] = "  $field: $message";
    }
    if ($response["old"]["name"] !== "") {
        $safe = htmlspecialchars($response["old"]["name"], ENT_QUOTES, "UTF-8");
        $lines[] = "  name box refilled with: $safe";
    }
    return implode("\n", $lines);
}

echo "GET  -> ", describe(handleContact("GET", [])), "\n";
echo "POST -> ", describe(handleContact("POST", ["name" => "", "email" => "nope"])), "\n";
$hostile = ["name" => "<b>Aye</b>", "email" => "aye@example"];
echo "POST -> ", describe(handleContact("POST", $hostile)), "\n";
$good = ["name" => "Aye", "email" => "aye@example.com"];
echo "POST -> ", describe(handleContact("POST", $good)), "\n";

Code breakdown

  1. Safe field readerreturn is_string($value) ? trim($value) : "";

    field() returns "" when the key is missing or the value is an array (name[]=x) and otherwise trims it, so the validation code always handles one plain string and never triggers a warning.

  2. Collect errors by field$errors["name"] = "Name is required.";

    Storing the error under the field name lets the form show the message beside the name input. Because validation does not stop at the first problem, the user sees every mistake in one pass.

  3. Method gateif ($method !== "POST") {

    On a GET it skips validation and shows the empty form, which prevents a "Name is required" error from appearing the first time the page is opened.

  4. Redirect resultreturn ["status" => 303, "location" => "/thanks"];

    Only a request with no errors reaches this path. In a real page this is where you save to a database and then run header("Location: /thanks", true, 303); exit;.

  5. Escaping the refill$safe = htmlspecialchars($response["old"]["name"], ENT_QUOTES, "UTF-8");

    The refill value is whatever the user typed, so it must be escaped on output. The angle brackets in <b>Aye</b> become HTML entity codes, so the browser no longer reads them as a tag (see the output).

You should see
GET  -> 200 empty form
POST -> 422 form again
  name: Name is required.
  email: Enter a valid email address.
POST -> 422 form again
  email: Enter a valid email address.
  name box refilled with: &lt;b&gt;Aye&lt;/b&gt;
POST -> 303 redirect to /thanks
The life of one form request
  1. Browser opens the page with GET
  2. PHP renders the empty form
  3. The user presses submit (POST)
  4. PHP validates every field
  5. The path splits on the result

Validation fails

422: show the form again with errors and the old values

Validation passes

Act, then 303 redirect: a refresh is now a harmless GET

Showing the form again: refill and escape

When you show a form again after errors, you must refill value="..." with what the user typed, otherwise their effort vanishes and they get frustrated. But a value placed inside an attribute may contain quotes, so use htmlspecialchars() with ENT_QUOTES to escape the characters that could break out of the attribute. The template below does this with one e() helper and shows a message only beside the field that has an error. In a template, <?= ... ?> is shorthand for echo.

form-template.php
<?php
$old = ["name" => 'Aye "Boss" <b>', "email" => ""];
$errors = ["email" => "Enter a valid email address."];
function e(string $text): string
{
    return htmlspecialchars($text, ENT_QUOTES, "UTF-8");
}
?>
<form method="post" action="">
  <label for="name">Name</label>
  <input id="name" name="name" value="<?= e($old["name"]) ?>">
  <label for="email">Email</label>
  <input id="email" name="email" type="email" value="<?= e($old["email"]) ?>">
<?php if (isset($errors["email"])): ?>
  <p class="error"><?= e($errors["email"]) ?></p>
<?php endif; ?>
  <button type="submit">Send</button>
</form>
text
<form method="post" action="">
  <label for="name">Name</label>
  <input id="name" name="name" value="Aye &quot;Boss&quot; &lt;b&gt;">
  <label for="email">Email</label>
  <input id="email" name="email" type="email" value="">
  <p class="error">Enter a valid email address.</p>
  <button type="submit">Send</button>
</form>

In this output the name input's quotes and angle brackets are turned into entity codes, so the attribute does not break, and only the email field gets an error paragraph below it. Keeping action="" sends the form to the current URL and avoids printing $_SERVER["PHP_SELF"] into HTML. Never refill a password field.

The real page: redirects and a CSRF token

To defend against CSRF, when you show the form you store a random token in the session and send it along in a hidden field. When the POST arrives, compare the session's token with the submitted one using hash_equals(), which is written to avoid timing attacks and is better than ==. The snippet below uses a $session array in place of $_SESSION, so the logic can be tried in the CLI.

csrf.php
<?php
function issueToken(array &$session): string
{
    $session["csrf"] = bin2hex(random_bytes(16));
    return $session["csrf"];
}

function tokenIsValid(array $session, mixed $submitted): bool
{
    return isset($session["csrf"]) && is_string($submitted)
        && hash_equals($session["csrf"], $submitted);
}

$session = [];   // stands in for $_SESSION
$token = issueToken($session);
echo strlen($token), " hex characters\n";
var_dump(tokenIsValid($session, $token));
var_dump(tokenIsValid($session, "forged"));
var_dump(tokenIsValid($session, null));
var_dump(tokenIsValid([], $token));

The output is 32 hex characters, then true, false, false, false: a token of 16 random bytes becomes 32 hex characters, only the genuine token yields true, and a forged value, a missing value and a missing session all give false. The code below shows the shape of a page that runs under a real web server. It is not executed here because session_start() and header() belong to a web request.

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

$errors = [];
$old = ["name" => "", "email" => ""];

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    if (!tokenIsValid($_SESSION, $_POST["csrf"] ?? null)) {
        http_response_code(403);
        exit("Invalid form token.");
    }
    $old = ["name" => field($_POST, "name"), "email" => field($_POST, "email")];
    $errors = validateContact($_POST);

    if ($errors === []) {
        saveMessage($old);                       // act: database, email ...
        $_SESSION["flash"] = "Thanks, we got your message.";
        header("Location: /contact.php", true, 303);
        exit;                                    // nothing runs after a redirect
    }
    http_response_code(422);
}
// render the form here: hidden csrf field, $errors, escaped $old values

In real projects

Where this shows up in real projects

Contact forms, logins, checkouts, profile settings and admin panels all follow this shape. Libraries such as Symfony Form and Laravel's validator manage the validate, errors, refill and redirect flow for you, but underneath it is the same, so understanding the pattern also explains a framework's error messages. Showing the "Thanks" message once after the redirect, as a flash message stored in the session and then removed, is common practice.

Production adds more to consider. With file uploads, add enctype="multipart/form-data" to the form and validate $_FILES separately, since the name, type and size are only claims. Reduce spam bots with rate limiting, CAPTCHAs or a honeypot field. Putting user text straight into an email header risks header injection through newline characters, so reject newlines. And do not trust prices or user ids in hidden fields; look them up again on the server.

Common mistakes

Common mistakes

1. Reading fields without checking the method

Reading $_POST["fname"] during a GET request prints Warning: Undefined array key "fname", which makes errors appear the first time the page opens. Read fields only inside REQUEST_METHOD === "POST" and give each one a ?? default.

2. Not redirecting after success

Showing the POST result directly lets a refresh plus a click on "resend" submit the form again, creating two orders or two messages. Use header("Location: ...", true, 303); exit; and remember that forgetting exit lets the code below keep running.

3. Refilling values without escaping them

With value="<?= $_POST['name'] ?>", a user who types " onfocus="alert(1) breaks out of the attribute and injects a script (XSS). Always go through an e() helper that calls htmlspecialchars($s, ENT_QUOTES, 'UTF-8').

4. Treating browser validation as real validation

required and type="email" are bypassed by switching off JavaScript, by editing the page in developer tools, or by POSTing directly with curl. Keep browser checks as a convenience and always validate on the server. Also do not trim() a password: spaces the user typed can be part of it.

Best practices

Best practices

  • Split the handler by REQUEST_METHOD, keep the validating function separate, and test it with array parameters.
  • Collect errors in an array keyed by field name and show them all at once; refill typed values escaped, but never a password.
  • Always end a successful POST with a 303 redirect and exit, and show the success message as a session flash.
  • Check a CSRF token with hash_equals() on every state-changing form, and use action="" instead of printing PHP_SELF into HTML.

Mini challenge

Mini challenge: a sign-up form validator

Write the validateSignup() function for a sign-up form. Check each field and return errors in an array keyed by field name, then print three test cases with report().

  • username: trimmed, and 3-20 letters, digits or underscores checked with preg_match
  • password: at least 8 characters (mb_strlen) and equal to password2; do not trim the password
  • age: validated with FILTER_VALIDATE_INT between 13 and 120
  • terms: a checkbox tested with isset(); report() prints valid, or invalid plus one line per error
signup.php
<?php
function validateSignup(array $post): array
{
    $errors = [];
    // TODO: username (trim, preg_match), password + password2 (no trim),
    // TODO: age with FILTER_VALIDATE_INT and a range, terms with isset()
    return $errors;
}

function report(array $post): void
{
    // TODO: print "valid", or "invalid" followed by "  field: message" lines
}

// TODO: one fully valid submission and two different invalid ones

Expected: Expected output: valid invalid username: Use 3-20 letters, digits or underscores. password: Use at least 8 characters. age: Age must be a whole number from 13 to 120. terms: You must accept the terms. invalid password: The two passwords do not match. age: Age must be a whole number from 13 to 120.

Show hint

$post["username"] may be an array, so check is_string() before trim(). Check the password length first and use elseif for the comparison with password2, so only one error appears. A filter_var result of false is what marks a bad age, so do not confuse it with 0. An unchecked checkbox sends no key, so use isset($post["terms"]).

Show solution
signup.php
<?php
function validateSignup(array $post): array
{
    $errors = [];
    $username = is_string($post["username"] ?? null) ? trim($post["username"]) : "";
    $password = is_string($post["password"] ?? null) ? $post["password"] : "";
    $confirm = is_string($post["password2"] ?? null) ? $post["password2"] : "";
    $age = is_string($post["age"] ?? null) ? trim($post["age"]) : "";

    if (preg_match('/^[A-Za-z0-9_]{3,20}$/', $username) !== 1) {
        $errors["username"] = "Use 3-20 letters, digits or underscores.";
    }
    if (mb_strlen($password) < 8) {
        $errors["password"] = "Use at least 8 characters.";
    } elseif ($password !== $confirm) {
        $errors["password"] = "The two passwords do not match.";
    }
    $range = ["options" => ["min_range" => 13, "max_range" => 120]];
    if (filter_var($age, FILTER_VALIDATE_INT, $range) === false) {
        $errors["age"] = "Age must be a whole number from 13 to 120.";
    }
    if (!isset($post["terms"])) {
        $errors["terms"] = "You must accept the terms.";
    }
    return $errors;
}

function report(array $post): void
{
    $errors = validateSignup($post);
    if ($errors === []) {
        echo "valid\n";
        return;
    }
    echo "invalid\n";
    foreach ($errors as $field => $message) {
        echo "  $field: $message\n";
    }
}

report(["username" => "aye_01", "password" => "s3cret-pass", "password2" => "s3cret-pass",
    "age" => "25", "terms" => "on"]);
report(["username" => "a!", "password" => "short", "password2" => "different",
    "age" => "9"]);
report(["username" => "min_2", "password" => "longenough1", "password2" => "longenough2",
    "age" => "abc", "terms" => "1"]);

Quick quiz 1 / 3

A checkbox <input type="checkbox" name="terms"> is left unchecked and the form is submitted. What does isset($_POST["terms"]) return?

Quick quiz 2 / 3

Why redirect with a Location header after a successful POST?

Quick quiz 3 / 3

A form field has required and type="email". Which statement is true?

What to remember

  • A form handler has five steps (render, submit, validate, act, redirect) and splits the GET and POST paths with REQUEST_METHOD.
  • Collect errors by field name and show them together; refill typed values escaped with ENT_QUOTES, but never a password.
  • End a successful POST with a 303 redirect and exit (PRG) so a refresh does not repeat the action.
  • Browser validation is only a convenience and server validation is always needed; test unchecked checkboxes with isset() and compare CSRF tokens with hash_equals().

PHP Security Manual — 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.

Handling Forms | Thuta Learning