What are best practices for displaying error messages in PHP forms?

When displaying error messages in PHP forms, it is important to provide clear and specific messages to the user to help them understand what went wrong. It is also essential to validate user input on the server side to prevent malicious data submission. Additionally, styling error messages differently from regular content can help draw attention to them.

<?php
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate form data
    if (empty($_POST["username"])) {
        $error = "Username is required";
    }
    // Display error message
    if (isset($error)) {
        echo '<div style="color: red;">' . $error . '</div>';
    }
}
?>