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 error reporting in PHP be utilized to troubleshoot issues with database queries?
- How can PHP be used to update an image file on a server with the current date and time information for display on a webpage?
- What are the best practices for handling session variables in PHP to ensure they are passed correctly between scripts?