×

php · level 2 · unit 4 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Never trust input until you have checked it.

Visitors make typos, skip boxes and sometimes send rubbish on purpose. So every field: check it is there, the right length and sensible, before you use it. If a was never sent, $_POST["name"] would crash, so read it with ?? "".

Use trim first, so a name made only of spaces counts as empty. Then collect a message for every problem in an $errors array, instead of stopping at the first one. The visitor can then fix everything in one go.

If $errors is still empty at the end, the form is good.

<?php
$_POST = ["name" => "  ", "message" => "Hi"];
$name = trim($_POST["name"] ?? "");
$message = trim($_POST["message"] ?? "");
$errors = [];
if ($name === "") {
    $errors[] = "Please tell us your name.";
}
if (strlen($message) < 5) {
    $errors[] = "Your message needs at least 5 characters.";
}
echo count($errors) === 0 ? "All good!\n" : implode("\n", $errors) . "\n";

Checks in the browser help visitors, but only checks in PHP keep your site safe, because anyone can fake a request.