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);
Related Questions
- How can the use of a DOM parser, such as DOMDocument, improve the handling of HTML or XML content in PHP compared to regex?
- How can the syntax and structure of PHP code impact the display and functionality of frames within a web page?
- Are there any potential pitfalls in using numerical indexes in PHP arrays?