php · level 2 · unit 4 · lesson 2
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Spaces, blanks and a missing field. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
$_POST = ["username" => " sam ", "age" => ""];
$username = trim($_POST["username"] ?? "");
$age = trim($_POST["age"] ?? "");
$town = trim($_POST["town"] ?? "");
echo strlen($username) . " " . strlen($age) . " " . strlen($town) . "\n";
your turn
Your turn. Get past the sign-up checks.
Type a username and a password, then run it. Try a short password first to see the error, then change your answers until you are welcomed.
fix it
A name made of spaces got through. Can you fix it?
- Three spaces are not the same as an empty string, so
$name === ""isfalse. - Cut the spaces off both ends before you check, so blank answers really are empty.
- Change line 3 to
$name = trim($_POST["name"] ?? "");, then press run.
nailed it
nothing gets past your checks now. :D
- Read every field with
?? "", thentrimit. - Collect every problem in an
$errorsarray. - Accept the form only when
$errorsis empty.
new words in your collection
- validate
- required field
This lesson isn’t saved. A free account remembers every lesson you finish.