How can PHP be used to efficiently validate and sanitize form input before sending it via email?

When sending form input via email, it is important to validate and sanitize the data to prevent malicious code injections or incorrect data being sent. PHP provides functions like filter_var() and htmlspecialchars() that can be used to validate and sanitize form input before sending it via email.

// Validate and sanitize form input
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$message = htmlspecialchars($_POST['message']);

// Send email with validated and sanitized data
$to = "recipient@example.com";
$subject = "Contact Form Submission";
$body = "Name: $name\nEmail: $email\nMessage: $message";
$headers = "From: sender@example.com";

// Send email
mail($to, $subject, $body, $headers);