What are the best practices for handling form submissions with PHP embedded within HTML output?

When handling form submissions with PHP embedded within HTML output, it is best practice to separate the PHP code from the HTML code to improve readability and maintainability. This can be achieved by processing the form submission at the top of the PHP script before any HTML output is generated. Additionally, using conditional statements to display success or error messages based on the form submission outcome is recommended.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Process form submission
    $name = $_POST["name"];
    $email = $_POST["email"];
    
    // Validate form data
    if (empty($name) || empty($email)) {
        $error_message = "Please fill out all fields.";
    } else {
        // Form submission successful
        $success_message = "Form submitted successfully!";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Form Submission</title>
</head>
<body>
    <?php if(isset($error_message)) { ?>
        <p><?php echo $error_message; ?></p>
    <?php } ?>
    
    <?php if(isset($success_message)) { ?>
        <p><?php echo $success_message; ?></p>
    <?php } ?>
    
    <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>
</body>
</html>