开发者

Complete protection against mail-injection

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

  • sender name
  • sender e-mail
  • subject
  • message body

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($_POS开发者_开发百科T['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


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.


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 ...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜