What are some best practices for handling form data in a single PHP file?

When handling form data in a single PHP file, it is important to properly sanitize and validate the input to prevent security vulnerabilities such as SQL injection or cross-site scripting attacks. Additionally, organizing the code to separate the form processing logic from the HTML presentation can improve readability and maintainability.

<?php
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Sanitize and validate form data
    $name = htmlspecialchars($_POST["name"]);
    $email = filter_var($_POST["email"], FILTER_VALIDATE_EMAIL);
    
    // Process the form data
    // Insert data into database, send email, etc.
    
    // Redirect after processing to prevent form resubmission
    header("Location: success.php");
    exit();
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Form Example</title>
</head>
<body>
    <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required>
        
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required>
        
        <button type="submit">Submit</button>
    </form>
</body>
</html>