What potential pitfalls should be considered when manipulating email headers in PHP?

When manipulating email headers in PHP, it is important to be cautious of potential security vulnerabilities such as header injection attacks. To prevent this, always sanitize and validate user input before using it in email headers. Additionally, be mindful of the format and encoding of the headers to ensure they are correctly interpreted by the email client.

// Sanitize and validate user input before using it in email headers
$subject = filter_var($_POST['subject'], FILTER_SANITIZE_STRING);
$to = filter_var($_POST['to'], FILTER_VALIDATE_EMAIL);

// Encode headers to prevent header injection attacks
$subject = mb_encode_mimeheader($subject, 'UTF-8');
$headers = "From: sender@example.com\r\n";
$headers .= "Reply-To: reply@example.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";

// Send email with sanitized and encoded headers
mail($to, $subject, $message, $headers);