What are the best practices for handling form submissions and displaying feedback messages in PHP?

When handling form submissions in PHP, it is important to properly validate user input and display appropriate feedback messages to the user. One common practice is to use conditional statements to check if the form has been submitted, validate the input, and display feedback messages accordingly.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate form input
    $name = $_POST["name"];
    
    if (empty($name)) {
        $error_message = "Name is required";
    } else {
        $success_message = "Form submitted successfully";
    }
}
?>

<form method="post" action="">
    <input type="text" name="name" placeholder="Name">
    <button type="submit">Submit</button>
</form>

<?php
if (isset($error_message)) {
    echo "<div style='color: red;'>$error_message</div>";
}

if (isset($success_message)) {
    echo "<div style='color: green;'>$success_message</div>";
}
?>