Skip to the workspace
Pebellslearn by building
HTTP Methods and Forms  ›  Lesson

$_POST and Processing a Form

$_POST 16 min$_POST contains parsed form fields for supported POST form encodings. Other bodies, such as JSON, need separate parsing, and all submitted data needs server-side validation.

php / $_POST and Processing a Form

Explore each scene at your own pace.

01 · The rule

The rule

$_POST and Processing a Form

$_POST contains parsed form fields for supported POST form encodings. Other bodies, such as JSON, need separate parsing, and all submitted data needs server-side validation.

Separate form submission, validation and escaped response output.

A visitor fills in Pageturn's order form: book, quantity, email. Those details must not sit in a bookmarkable URL, and submitting them creates an order. That is a job for POST, and every PHP form follows the same short recipe.

The rule

Check the method, validate every field, act, then redirect.

The form:

<form method="post" action="order.php">
  <input name="title" value="Dune">
  <input name="qty" type="number" value="1">
  <input name="email" type="email">
  <button>Order</button>
</form>

Each input's name becomes a key in $_POST. The data travels in the request body, not the URL. The script:

<?php
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $qty   = filter_var($_POST['qty'] ?? '', FILTER_VALIDATE_INT);
    $email = filter_var($_POST['email'] ?? '', FILTER_VALIDATE_EMAIL);

    if ($qty === false || $qty < 1) {
        $errors[] = 'Quantity must be a whole number of at least 1.';
    }
    if ($email === false) {
        $errors[] = 'Please enter a valid email address.';
    }

    if (!$errors) {
        saveOrder($_POST['title'], $qty, $email);
        header('Location: thanks.php');   // redirect after success
        exit;
    }
}
// otherwise show the form again, with $errors escaped and listed

The recipe, step by step:

  1. Check the method. The same script often shows the form (GET) and handles it (POST). $_SERVER['REQUEST_METHOD'] tells you which.
  2. Validate every field. Like $_GET, $_POST is text sent by the visitor, and it can be missing or crafted by hand. filter_var returns the clean value, or false when it does not fit. Browser checks such as type="email" help honest visitors but stop no one else.
  3. Act only when there are no errors.
  4. Redirect. Send a Location header and exit. Without this, pressing Refresh on the result page resubmits the form and orders a second copy. This pattern is called Post/Redirect/Get.

When validation fails, show the form again with the messages, escaping everything you print back with htmlspecialchars().

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.