In PHP, what are the recommended methods for handling form submissions and displaying error messages to users effectively?

When handling form submissions in PHP, it is recommended to validate user input to ensure data integrity and security. Displaying error messages to users in a clear and concise manner can help improve user experience. One way to achieve this is by using conditional statements to check for errors and displaying appropriate messages to the user.

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

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
    <input type="text" name="name" placeholder="Name">
    <button type="submit">Submit</button>
</form>

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