What are the best practices for optimizing PHP code when dealing with form submissions and mail functions?

When dealing with form submissions and mail functions in PHP, it is essential to optimize the code to ensure efficient processing and prevent potential security vulnerabilities. One way to achieve this is by sanitizing and validating user input before processing it further. Additionally, using built-in PHP functions for sending emails, such as `mail()`, can help streamline the process and reduce the risk of errors.

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

// Send email using PHP mail function
$to = "recipient@example.com";
$subject = "Contact Form Submission";
$headers = "From: $email";
$body = "Name: $name\nEmail: $email\nMessage: $message";

if (mail($to, $subject, $body, $headers)) {
    echo "Email sent successfully!";
} else {
    echo "Failed to send email. Please try again.";
}