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 basename() be utilized to remove file extensions in PHP scripts, and what considerations should be made when applying this function to multiple files?
- What are the advantages and disadvantages of using pre-built forum systems like phpBB or WoltLab versus creating a custom forum system in PHP?
- What is the purpose of the $_GET superglobal in PHP and how is it used in this specific code snippet?