This section contains the detail about Prevention against email injections in PHP.
Prevention against email injections
First you need to know what is email injection.
Email injection is the a security vulnerability that can occur in Internet applications that are used to send e-mail messages.
This email injection sends unwanted emails to different addresses.
The code given in previous tutorial(click here) has a serious security threat. It has email injection problem. If you insert data into the mail headers via the input form as given below :
person1@example.com%0ACc:person2@example.com %0ABcc:person3@example.com,person3@example.com, anotherperson4@example.com,person5@example.com %0ABTo:person6@example.com
After form submission., it will add to the mail headers and as a result header has an extra Cc:, Bcc:, and To: field. Due to this, the mail will be sent to all the mail address above.
How it can be prevent from email injections
The most efficient way to stop email injection is to validate the email input field.
Use the following function to prevent email injection :
<?php function spamcheck($field) { //filter_var() sanitizes the e-mail //address using FILTER_SANITIZE_EMAIL $field=filter_var($field, FILTER_SANITIZE_EMAIL); //filter_var() validates the e-mail //address using FILTER_VALIDATE_EMAIL if(filter_var($field, FILTER_VALIDATE_EMAIL)) { return TRUE; } else { return FALSE; } } ?>
Use it as follows :
if (isset($_REQUEST['email'])) {//if "email" is filled out, proceed //check if the email address is invalid $mailcheck = spamcheck($_REQUEST['email']); if ($mailcheck==FALSE) { echo "Invalid input"; } else { //send email } }
In the above code, we use two PHP filters to validate input :
1. FILTER_SANITIZE_EMAIL : removes all illegal e-mail characters from a string.
2. FILTER_VALIDATE_EMAIL : validates value as an e-mail address.
[ 0 ] Comments