How can the issue of Mail Header Injection be mitigated in PHP scripts to prevent spamming?
Mail Header Injection occurs when user input is not properly sanitized before being used in email headers, allowing an attacker to inject additional headers into the email. To prevent this, always validate and sanitize user input before using it in email headers.
// Sanitize user input for email headers
$to = filter_var($_POST['to'], FILTER_SANITIZE_EMAIL);
$subject = filter_var($_POST['subject'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
// Set additional headers to prevent Mail Header Injection
$headers = "From: webmaster@example.com\r\n";
$headers .= "Reply-To: webmaster@example.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
// Send the email
mail($to, $subject, $message, $headers);