What are the best practices for preventing mail() header-injection in PHP applications?
Mail() header injection can occur when user input is not properly sanitized before being included in email headers, allowing malicious users to inject additional headers that could potentially be used for phishing attacks. To prevent this, always validate and sanitize user input before using it in email headers. Example PHP code snippet to prevent mail() header injection:
// Sanitize the user input before using it in 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 header injection
$headers = "From: yourname@example.com\r\n";
$headers .= "Reply-To: yourname@example.com\r\n";
$headers .= "X-Mailer: PHP/" . phpversion();
// Send the email using the sanitized input and additional headers
mail($to, $subject, $message, $headers);
Related Questions
- Are there any best practices to keep in mind when using preg_match with special characters like umlauts in PHP?
- Was bedeutet es, dass require() eine Datei "einbindet und auswertet" im Vergleich zu include()?
- How can PHP developers ensure smooth file upload and deletion processes when working with FTP in their scripts?