What are the best practices for handling form data submission in PHP to ensure data integrity and accurate email notifications?

To ensure data integrity and accurate email notifications when handling form data submission in PHP, it is important to validate the input data to prevent SQL injection and other security vulnerabilities. Additionally, sanitize the input data to remove any potentially harmful characters. Finally, use proper error handling techniques to notify users of any issues with their submission and send email notifications to the appropriate recipients upon successful form submission.

<?php
// Validate input data
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);

// Sanitize input data
$name = htmlspecialchars($name);
$email = htmlspecialchars($email);
$message = htmlspecialchars($message);

// Send email notification
$to = "recipient@example.com";
$subject = "New form submission";
$body = "Name: $name\nEmail: $email\nMessage: $message";
$headers = "From: sender@example.com";

if (mail($to, $subject, $body, $headers)) {
    echo "Email sent successfully";
} else {
    echo "Failed to send email";
}
?>