Your Common Sense
Your Common Sense

Reputation: 158007

Complete protection against mail-injection

Suppose we're sending trivial feedback and going to make these fields dynamic:

would be this PHP code enough to protect us from all kinds of mail-injections?

  //sanitizing email address
if ($email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
  //encoding subj according to RFC and thus protecting it from all kinds of injections
  $subject = "=?UTF-8?B?".base64_encode($_POST['subject'])."?=";
  //encoding name for same reasons, and using sanitized email
  $from    = "From: =?UTF-8?B?".base64_encode($_POST['name'])."?= <$email>\r\n";
  //protecting body as it mentioned in http://php.net/mail
  $message = str_replace("\n.", "\n .", $_POST['text']);
  mail('me@example.com',$subject,$message,$from);
}

at the moment I am playing with names like "some@email.com, other@email.com," but it seems that all available mail clients handling it correctly

Upvotes: 3

Views: 515

Answers (2)

Charles
Charles

Reputation: 51421

would be this PHP code enough to protect us from all kinds of mail-injections?

It looks pretty comprehensive, just as long as your email client supports the RFC 2047 encoding method you're using in the headers. (Some webmail clients don't recognize the encoding.)

My only recommendation, other than not using mail() to begin with, would be considering is_email rather than the built-in filter. The built-in fails a number of edge cases.

Upvotes: 2

yent
yent

Reputation: 1343

It depends, if the filter complies with rfc that specify that the local part cant contain anything if it is surrounded by " or whatever character some address like "foo\r\nTo: poor-guy@dom.tld\r\nTo: dummy"@foo.tld will give you headers like :

Subject: foo
To: poor-guy@dom.tld
To: dummy"@foo.tld

quite bad ...

Upvotes: 0

Related Questions