What are the best practices for handling form submissions in PHP and displaying error messages using modal boxes?

When handling form submissions in PHP and displaying error messages using modal boxes, it is important to validate user input server-side to prevent any malicious data from being submitted. Once the form is submitted, check for any errors and display them in a modal box using JavaScript. This provides a more user-friendly way to alert users of any issues with their submission.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate form data
    $name = $_POST["name"];
    if (empty($name)) {
        $error = "Name is required.";
    }

    // If there are no errors, process the form submission
    if (empty($error)) {
        // Process form data
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Form Submission</title>
    <script>
        // Display error message in modal box
        <?php if (!empty($error)) { ?>
            window.onload = function() {
                alert("<?php echo $error; ?>");
            };
        <?php } ?>
    </script>
</head>
<body>
    <form method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>">
        <input type="text" name="name" placeholder="Name">
        <button type="submit">Submit</button>
    </form>
</body>
</html>