Are there any specific best practices for handling form submissions and validations in PHP to ensure a smooth user experience?

When handling form submissions and validations in PHP, it is essential to ensure a smooth user experience by providing clear error messages and feedback. One best practice is to validate user input on the server-side to prevent malicious attacks or incorrect data from being submitted. Additionally, using functions like filter_var() or regular expressions can help validate form inputs effectively.

<?php
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    // Validate form inputs
    $name = $_POST["name"];
    $email = $_POST["email"];
    
    if (empty($name) || empty($email)) {
        $error = "Please fill in all fields.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Invalid email format.";
    } else {
        // Process form submission
        // Insert data into database, send email, etc.
        $success = "Form submitted successfully!";
    }
}
?>

<!-- Display form and error/success messages -->
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <input type="text" name="name" placeholder="Name">
    <input type="email" name="email" placeholder="Email">
    <button type="submit">Submit</button>
</form>

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