Wikiup
Wikiup

Reputation: 325

What's current best practice to prevent email injection attacks in PHP?

What's considered the best practice these days for sanitizing data from a PHP email form?

I'm currently using something like this...

$msg = $_POST['msg'];
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$name = $_POST['name'];

$subject = "Message from the MY_WEBSITE website e-mail system";
$message = "From: " . $name . "\n";
$message .= "Email: " . $email . "\n\n";
$message .= $msg;
$headers = "From: " . $email . "\r\n" .
           "Reply-To: " . $email . "\r\n" .
           "X-Mailer: PHP/" . phpversion();

$mailSuccess = mail("[email protected]", $subject, $message, $headers);

Is it sufficient protection to simply filter the email field in this fashion? Can/should I harden the script more effectively to protect against spammers?

Thanks in advance!

[EDIT]Clarification, since the answers so far suggest that I've not explained myself well.

I'm not principally concerned with spambots getting hold of this script, but with anyone utilizing it to send illicit emails to any address other than [email protected]. This might include a bot, but could equally be a human defeating a CAPTCHA test.

What I'm looking for is PHP that will ensure that the email sent by the mail() method is not hijacked. This is probably a regex or filter or similar that simply strips certain characters. Thanks again.[/EDIT]

Upvotes: 3

Views: 3535

Answers (1)

cletus
cletus

Reputation: 625097

I would do this:

  • Use CAPTCHA;
  • Fail to send if the subject or body includes any HTML tags whatsoever. Note: I didn't say strip them out. Just don't send the email and give an error message to the user why. There's no point sending yourself a filtered spam message. Just don't send it;
  • strip out any high or low characters (filter_vars() can do this);
  • limit the message to, say, 4000 characters (or some other appropriate limit that you pick);
  • fail if the message contains any URL that doesn't point to the current site;
  • arguably use some of the techniques from How do you stop scripters from slamming your website hundreds of times a second? to ensure there is a human sending the message.

Upvotes: 2

Related Questions