PHP e-Mail injection
First, take a look at the PHP code in the chapter:
<body>
<?php
if (isset ($_request[' email '))
If "email" is filled out, send email
{
Send email
$email = $_request[' email '];
$subject = $_request[' subject ');
$message = $_request[' message '];
Mail ("[email protected]", "Subject: $subject",
$message, "From: $email");
echo "Thank you to using our mail form";
}
Else
If "email" is not filled out, display the form
{
echo "<form method= ' post ' action= ' mailform.php ' >
Email: <input name= ' email ' type= ' text ' ><br>
Subject: <input name= ' Subject ' type= ' text ' ><br>
Message:<br>
<textarea name= ' message ' rows= ' cols= ' >
</textarea><br>
<input type= ' Submit ' >
</form> ";
}
?>
</body>
The problem with the above code is that an unauthorized user can insert data into the header of the message by entering the form.
What happens if the user adds the following text to the e-mail message in the form's input box?
[Email Protected]%0acc:[email protected]
%0abcc:[email Protected],[email protected],
[Email Protected],[email protected]
%0abto:[email protected]
As always, the mail () function puts the above text in the header of the message, and now the head has an extra Cc:, BCC: And to: Fields. When the user clicks the Submit button, the e-mail will be sent to all the addresses above!
PHP prevents e-mail injection
The best way to prevent e-mail injection is to validate the input.
The following code is similar to the one in the previous chapter, but here we have added an input validator for the email field in the detection form:
<body>
<?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;
}
}
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
$email = $_request[' email '];
$subject = $_request[' subject ');
$message = $_request[' message '];
Mail ("[email protected]", "Subject: $subject",
$message, "From: $email");
echo "Thank you to using our mail form";
}
}
Else
{//if "email" is not filled out, display the form
echo "<form method= ' post ' action= ' mailform.php ' >
Email: <input name= ' email ' type= ' text ' ><br>
Subject: <input name= ' Subject ' type= ' text ' ><br>
Message:<br>
<textarea name= ' message ' rows= ' cols= ' >
</textarea><br>
<input type= ' Submit ' >
</form> ";
}
?>
</body>
In the code above, we used a PHP filter to validate the input:
- Filter_sanitize_email filter removes illegal characters from a string in an e-mail message
- Filter_validate_email Filter Verify the value of the e-mail address
You can read more about filters in our PHP filter.
PHP e-Mail