How can PHP code be improved to ensure correct handling of form data before sending emails?

To ensure correct handling of form data before sending emails in PHP, it is important to validate and sanitize the input data to prevent security vulnerabilities and ensure that the email is sent correctly. This can be done by using PHP functions like filter_var() for validation and filter_input() for sanitization. Additionally, checking for any required fields and implementing proper error handling can help improve the reliability of the email sending process.

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

// Check for required fields
if(empty($name) || empty($email) || empty($message)) {
    echo "Please fill out all required fields.";
} else {
    // Send email
    $to = "recipient@example.com";
    $subject = "Contact Form Submission";
    $headers = "From: $name <$email>";
    
    if(mail($to, $subject, $message, $headers)) {
        echo "Email sent successfully.";
    } else {
        echo "Failed to send email. Please try again later.";
    }
}