PHP Secure Email
PHP E-mail
PHP Error
In the PHP e-mail script in the previous section, there is a vulnerability.
PHP E-mail Injection
First, look at the PHP code in the previous section:
Email:
Subject:
Message:
"; } ?>
The problem with the above code is that unauthorized users can insert data in the email header through the input form.
What will happen if the user adds these texts to the input box in the form?
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 additional Cc:, Bcc: and To: fields. When the user clicks the submit button, this e-mail will be sent to all the addresses above!
PHP Prevent E-mail Injection
The best way to prevent e-mail injection is to validate the input.
The following code is similar to the previous section, but we have added an input validator to detect the email field in the form:
Email:
Subject:
Message:
"; } ?>
In the above code, we use a PHP filter to validate the input:
FILTER_SANITIZE_EMAIL Remove illegal characters of email from string
FILTER_VALIDATE_EMAIL Verify email address