What are the best practices for structuring PHP code to ensure that form submission data is processed correctly and displayed accurately?

When processing form submission data in PHP, it is important to structure your code in a way that ensures data validation, sanitization, and proper display. To achieve this, you can create a separate PHP file to handle form submission, validate the input data, sanitize it to prevent SQL injection or XSS attacks, and then display the processed data on the webpage.

<?php
// form_submission.php

// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate and sanitize form data
    $name = htmlspecialchars(trim($_POST["name"]));
    $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
    $message = htmlspecialchars(trim($_POST["message"]));

    // Display the processed data
    echo "Name: " . $name . "<br>";
    echo "Email: " . $email . "<br>";
    echo "Message: " . $message . "<br>";
}
?>