CodeBlanks Logo Icon CodeBlanks

Showing error messages

PHP course · Beginner · Lesson 104/116

Learn to show validation errors to the user next to the form.

Collecting errors in an array

Collect validation errors in an array and show them next to the form. This both informs the user and keeps the code readable. Example: start with $errors = [];, add with $errors[] = "Name empty";. Then with if ($errors) you print each one.

Error messages should be clear and polite. "Name empty" is weaker than "Please enter your name". When you re-show the form, also write back the previously entered values; the user does not have to start over.

Showing errors with foreach

To show the errors you loop the array with foreach: foreach ($errors as $error) { echo "<li>" . htmlspecialchars($error) . "</li>"; }. You also escape the error message with htmlspecialchars(); like a username, error text can be an XSS vector too.

When you re-show the form, write the previous value inside value="": value="<?php echo htmlspecialchars($name ?? ''); ?>". The user can then fix a wrong entry and re-submit.

Exercise Collect errors and print them

Start with $errors = [];. Set $name = "";. Inside if (empty($name)) write $errors[] = "Name required";. Then inside if ($errors) use foreach ($errors as $error) to write echo $error . "\n";.

Show example solution
First write $errors = []; and $name = "";. Then add if (empty($name)) { $errors[] = "Name required"; } and if ($errors) { foreach ($errors as $error) { echo $error . "\n"; } }.
Example solution:
<?php
// Collect errors and print them
$errors = [];
$name = "";
if (empty($name)) {
    $errors[] = "Name required";
}
if ($errors) {
    foreach ($errors as $error) {
        echo $error . "\n";
    }
}

Test yourself

  1. Add an error to the errors array

    $errors____ = "Name empty";
    Show answer
    $errors[] = "Name empty";
  2. Match the error flow steps

    $errors = []
    Init empty array
    $errors[] = ...
    Add new error
    foreach ($errors as $error)
    Loop errors
    htmlspecialchars($error)
    Print error safely
  3. Why escape error messages with htmlspecialchars?

    • To colour the error messages
    • Because error text may also contain user input
    • Because htmlspecialchars deletes errors
    • To speed up validation
    Show answer

    Because error text may also contain user input — Correct. Error text can come from user input, so it can be an XSS vector; escaping keeps you safe.

All lessons in Beginner