How does mail() header-injection work in PHP and what are the potential risks?
Mail() header injection in PHP occurs when user input is not properly sanitized before being included in email headers, allowing malicious users to inject additional headers or manipulate existing ones. This can lead to email header injection attacks, such as sending spam emails or phishing attempts. To prevent this, always sanitize user input and use proper encoding when constructing email headers.
// Fix for preventing mail() header injection
$to = 'recipient@example.com';
$subject = 'Test Subject';
$message = 'This is a test message';
$headers = 'From: sender@example.com' . "\r\n";
$headers .= 'Reply-To: sender@example.com' . "\r\n";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Sanitize user input before using it in headers
$cleaned_subject = filter_var($subject, FILTER_SANITIZE_STRING);
$cleaned_message = filter_var($message, FILTER_SANITIZE_STRING);
// Send the email using sanitized headers
mail($to, $cleaned_subject, $cleaned_message, $headers);
Keywords
Related Questions
- Are there best practices for handling time calculations in PHP to avoid incorrect results?
- Are there any specific PHP libraries or frameworks that specialize in mathematical calculations?
- What are the advantages and disadvantages of using spl_object_hash() versus custom methods for identifying object instances in PHP?