Skip to content
PHP Logo

How can PHP scripts be vulnerable to spam email injection?

PHP scripts can be vulnerable to spam email injection if they do not properly sanitize user input before using it to construct email messages. To prevent this vulnerability, always validate and sanitize user input, especially when constructing email headers or content.

php
// Sanitize user input before using it in email headers
$subject = filter_var($_POST['subject'], FILTER_SANITIZE_STRING);
$from_email = filter_var($_POST['from_email'], FILTER_SANITIZE_EMAIL);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);

// Construct email headers
$headers = "From: $from_email" . "\r\n" .
           "Reply-To: $from_email" . "\r\n" .
           "X-Mailer: PHP/" . phpversion();

// Send email
mail("recipient@example.com", $subject, $message, $headers);