全面防范邮件注入
假设我们要发送简单的反馈并让这些字段动态化:
- 发件人姓名
- 发件人电子邮件
- 主题
- 消息正文
这段 PHP 代码足以保护我们免受各种邮件注入吗?
//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('[email protected]',$subject,$message,$from);
}
目前我正在使用诸如 "[email protected], [email protected],"
但似乎所有可用的邮件客户端都正确处理它
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它看起来相当全面,只要您的电子邮件客户端支持 RFC 2047 编码方法您在标题中使用。 (某些网络邮件客户端无法识别该编码。)
除了一开始不使用
mail()
之外,我唯一的建议是考虑 is_email 而不是内置过滤器。内置功能无法解决许多边缘情况。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.这取决于过滤器是否符合 rfc 规定,如果本地部分被 " 或任何字符包围,则本地部分不能包含任何内容,例如 "foo\r\nTo: [email protected]\r\nTo: dummy"@foo.tld 会给你这样的标题:
相当糟糕......
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: [email protected]\r\nTo: dummy"@foo.tld will give you headers like :
quite bad ...