Summary - Forms
Build a registration form combining form, $_POST and htmlspecialchars.
Summary - Forms
In this group you learned to create a form, read data with $_POST, stop XSS with htmlspecialchars(), validate with empty() and filter_var(), and show error messages.
The flow of a registration page is: show the form → detect submission → read data from $_POST → check empty fields with empty() and the email with filter_var() → collect errors in an array → if no errors, thank the user; otherwise re-show the form and print the errors.
Exercise Process the registration form
Set $_POST['name'] = "";. Set $_POST['email'] = "bad";. Start with $errors = [];. Inside if (empty($_POST['name'])) write $errors[] = "Name required";. Inside if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) write $errors[] = "Invalid email";. Then inside if ($errors) use foreach ($errors as $error) to write echo $error . "\n";, and in the else block write echo "Welcome, " . htmlspecialchars($_POST['name']) . "!";.
Show example solution
First write $_POST['name'] = ""; and $_POST['email'] = "bad";, start with $errors = [];. Collect errors in two ifs. Then add if ($errors) { foreach ($errors as $error) { echo $error . "\n"; } } else { echo "Welcome, " . htmlspecialchars($_POST['name']) . "!"; }.
Example solution:
<?php
// Process the registration form
$_POST['name'] = "";
$_POST['email'] = "bad";
$errors = [];
if (empty($_POST['name'])) {
$errors[] = "Name required";
}
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email";
}
if ($errors) {
foreach ($errors as $error) {
echo $error . "\n";
}
} else {
echo "Welcome, " . htmlspecialchars($_POST['name']) . "!";
}
Test yourself
-
What should the first step in a registration form be?
- Write the form straight to the database
- Trust the user data as is
- Show the form and read data with $_POST
- Ignore the errors
Show answer
Show the form and read data with $_POST — Correct. First show the form; when submitted, read the data with $_POST.
-
Match the summary concepts
- method="post"
- Sends data in the body
- $_POST['name']
- Reads the field value
- empty()
- Catches empty fields
- htmlspecialchars()
- Stops XSS
-
Complete the htmlspecialchars call in the summary
echo ____($_POST['name'], ENT_QUOTES);Show answer
echo htmlspecialchars($_POST['name'], ENT_QUOTES);