How does mail() header-injection work in PHP and what are the potential risks?

Mail() header injection in PHP occurs when user input is not properly sanitized before being included in email headers, allowing malicious users to inject additional headers or manipulate existing ones. This can lead to email header injection attacks, such as sending spam emails or phishing attempts. To prevent this, always sanitize user input and use proper encoding when constructing email headers.

// Fix for preventing mail() header injection
$to = 'recipient@example.com';
$subject = 'Test Subject';
$message = 'This is a test message';
$headers = 'From: sender@example.com' . "\r\n";
$headers .= 'Reply-To: sender@example.com' . "\r\n";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

// Sanitize user input before using it in headers
$cleaned_subject = filter_var($subject, FILTER_SANITIZE_STRING);
$cleaned_message = filter_var($message, FILTER_SANITIZE_STRING);

// Send the email using sanitized headers
mail($to, $cleaned_subject, $cleaned_message, $headers);