How can mail-header-injection vulnerabilities be prevented when sending emails using PHP's mail function?
Mail-header-injection vulnerabilities can be prevented by sanitizing user input before including it in the email headers. This can be achieved by validating and filtering the input to ensure it does not contain any special characters that could be used to inject additional headers. Additionally, using the PHP `mb_encode_mimeheader` function to encode any potentially dangerous characters can help mitigate the risk of injection attacks.
$to = 'recipient@example.com';
$subject = 'Subject of the email';
$message = 'Body of the email';
// Sanitize user input to prevent header injection
$cleaned_subject = filter_var($subject, FILTER_SANITIZE_STRING);
$cleaned_message = filter_var($message, FILTER_SANITIZE_STRING);
// Encode potentially dangerous characters in the subject
$encoded_subject = mb_encode_mimeheader($cleaned_subject);
// Send the email with sanitized and encoded headers
mail($to, $encoded_subject, $cleaned_message);