"proper prevention of mail injection in php" Answer’s


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';

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.


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']);
Wednesday, March 31, 2021
answered 10 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :