PHP Secure E-mails
There is a vulnerability in the PHP e-mail script from the previous section.
PHP E-mail Injection
First, please look at the PHP code from the previous chapter:
Runoob Tutorial(runoob.com)
Email:
Subject:
Message:
";
}
?>
The problem with the above code is that unauthorized users can insert data into the email header through an input form.
What happens if a user adds the following text into the input box in the form to the email?
someone@example.com%0ACc:person2@example.com
%0ABcc:person3@example.com,person3@example.com,
anotherperson4@example.com,person5@example.com
%0ABTo:person6@example.com
As usual, the mail() function puts the above text into the email header, so now the header has extra Cc:, Bcc: and To: fields. When the user clicks the submit button, this e-mail will be sent to all the addresses above!
PHP Preventing E-mail Injection
The best way to prevent e-mail injection is to validate the input.
The code below is similar to that in the previous chapter, but here we have added input validation to check the email field in the form:
Runoob Tutorial(runoob.com)
Email:
Subject:
Message:
";
}
?>
In the code above, we used the PHP filter to validate the input:
- The FILTER_SANITIZE_EMAIL filter removes illegal characters from an email string
- The FILTER_VALIDATE_EMAIL filter validates the value of an email address
You can find it in our PHP Filter Read more about filters.