Stopping E-Mail Injection PHP

Soldato
Joined
30 Nov 2005
Posts
3,084
Location
London
How safe is the following code?

Is it E-Mail injection proof?

What would I need to do to increase security?

I've heard of header hijacking and using the form to spam other e-mail addresses by inserting them into the header.

PHP:
$email = $_POST['email'] ;
$to = "[email protected]";
$subject = "FORM Name";
$message = "The contents of email";

$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";


$headers .= "From: $email" . "\r\n" .
"CC: $email";


mail($to,$subject,$message,$headers);
header("Location:thankyou.php");
 
Last edited:
Don't forge their email in the headers and you'll be fine. If yours/their email systems use SPF (spam filtering) it might get marked as spam for it anyway (SPF lists which IP addresses are allowed to send email for that domain).

Just let it default to [email protected].
 
Remove all white space from email addresses. It's not semantically correct, but generally speaking, it'll do.
PHP:
$email = preg_replace("/\s/mg", $_POST['email']);
Otherwise I could submit the following:
Code:
<form action="yourpage.php" method="post">
  <input name="email" value="[email protected]
Reply-To: [email protected]
Content-Type: multipart/mixed; boundary=&quot;----foo----&quot;
Content-Transfer-Encoding: 7bit

----foo----
<7bit encoded binary for virus.exe>

----foo----
<7bit encoded binary for sexy.exe>" />
  <input type="submit">
</form>
 
Last edited:
This:
PHP:
$headers .= "From: $email" . "\r\n" .
"CC: $email";

It'll work fine without any headers at all:
PHP:
mail($to,$subject,$message)
 
Back
Top Bottom