How can PHP developers ensure that email headers are not vulnerable to header injection attacks when sending emails?

To prevent header injection attacks when sending emails in PHP, developers should sanitize user input and validate email addresses before using them in email headers. One way to achieve this is by using the `filter_var()` function with the `FILTER_VALIDATE_EMAIL` filter to validate email addresses.

// Sanitize and validate email address
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);

if ($email) {
    // Send email with sanitized email address
    $headers = "From: webmaster@example.com\r\n";
    $headers .= "Reply-To: $email\r\n";
    
    $subject = "Subject of the email";
    $message = "Body of the email";
    
    mail("recipient@example.com", $subject, $message, $headers);
} else {
    // Handle invalid email address
    echo "Invalid email address";
}