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 rn
, 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()
: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 PHPmail()
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: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: