Skip to content
PHP Logo

What are common issues when outputting error messages in PHP forms?

Common issues when outputting error messages in PHP forms include not properly displaying the error messages to the user, displaying generic error messages instead of specific ones, and not properly validating user input before displaying error messages. To solve these issues, ensure that error messages are clearly displayed next to the corresponding form fields, provide specific error messages that guide users on how to correct their input, and validate user input using PHP functions like `filter_var()` or regular expressions before displaying any error messages.

php
<?php
// Example code snippet demonstrating how to properly display error messages in a PHP form

$errors = [];

// Validate form input
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $email = $_POST["email"];

    if (empty($email)) {
        $errors["email"] = "Email is required";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors["email"] = "Invalid email format";
    }

    // Display error messages next to form fields
    if (!empty($errors)) {
        foreach ($errors as $error) {
            echo "<p class='error'>$error</p>";
        }
    }
}
?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <input type="text" name="email" placeholder="Email" value="<?php echo isset($_POST['email']) ? $_POST['email'] : ''; ?>">
    <button type="submit">Submit</button>
</form>