在PHP中正确预防邮件注入 [英] Proper prevention of mail injection in PHP
问题描述
mail()中阻止电子邮件注入
而不会丢失原始消息数据?例如。如果我需要允许用户使用 \r\\\
,到
, CC
等等,所以我不想完全剥离他们的消息 - 我仍然希望他们交付,但没有添加任何额外的标题,或以某种方式允许邮件注入发生。 互联网上的大多数建议都是完全剥离这些数据,但我不想这样做。
我发送纯文本(非HTML)消息通过PHP mail()
功能。
你会建议什么?
要过滤收件人电子邮件字段中使用的有效电子邮件,请查看 filter_var()
:
$ email = filter_var($ _ POST ['recipient_email'],FILTER_VALIDATE_EMAIL);
if($ email === FALSE){
echo'Invalid email';
exit(1);
}
这将确保您的用户只提供单一的有效电子邮件,您可以然后传递给 mail()
函数。据我所知,没有办法通过邮件正文使用PHP mail()
函数来注入头文件,因此数据不需要任何特殊的处理。 p>
更新:
根据 mail()
的文档,当它直接与... SMTP服务器,您需要防止邮件正文中的完整停止:
$ body = str_replace(\\\
,\\\
..,$ body);
更新#2:
显然,也可以通过主题注入,但由于没有 FILTER_VALIDATE_EMAIL_SUBJECT
,您需要自己进行过滤: / p>
$ subject = str_ireplace(array(\r,\\\
,'%0A','%0D '','',$ _POST ['subject']);
Could you advise me how do I go about preventing email injection in PHP mail()
without losing original message data? E.g. if I need to allow user to use \r\n
, To
, CC
etc, so I do not want to completely strip them away from the message - I still want them delivered, but without adding any additional headers or somehow allowing mail injection to happen.
Most of the advices on internet suggest stripping that data away completely - but I do not want to do that.
I am sending plain text (non HTML) messages through PHP mail()
function.
What would you advise?
To filter valid emails for use in the recipient email field, take a look at filter_var()
:
$email = filter_var($_POST['recipient_email'], FILTER_VALIDATE_EMAIL);
if ($email === FALSE) {
echo 'Invalid email';
exit(1);
}
This will make sure your users only supply singular, valid emails, which you can then pass to the mail()
function. As far as I know, there's no way to inject headers through the message body using the PHP mail()
function, so that data shouldn't need any special processing.
Update:
According to the documentation for mail()
, when it's talking directly to an SMTP server, you will need to prevent full stops in the message body:
$body = str_replace("\n.", "\n..", $body);
Update #2:
Apparently, it's also possible to inject via the subject, as well, but since there is no FILTER_VALIDATE_EMAIL_SUBJECT
, you'll need to do the filtering yourself:
$subject = str_ireplace(array("\r", "\n", '%0A', '%0D'), '', $_POST['subject']);
这篇关于在PHP中正确预防邮件注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!