How to secure a web contact form
Many people have “contact us” forms on their website (or some other kind of form that sends email out using PHP).

A solution to send out the form by email might be the following:
<?php
$from =$_POST[from_address'];
$message=$_POST['message'];
$to = "webmaster@mydomain.com";
mail($to,'web contact form',$message,"From: $from\n");
?>
$from =$_POST[from_address'];
$message=$_POST['message'];
$to = "webmaster@mydomain.com";
mail($to,'web contact form',$message,"From: $from\n");
?>
The problem with the above code is that it allows spammers to inject headers into the email, giving them the ability to send email anyone.
It can be done through the From field:
spam@email.com%0Acc:spam2@email.com
Your script will see the %0A as a newline and the headers will be sent like this:
| To: | you@yourcompany.com |
| From: | spam@email.com |
| cc: | spam2@email.com |
The fix
A way to fix this potential issue is to validate the from address with a regular expression:
<?php
$from =$_POST[from_address'];
$message=$_POST['message'];
$to = "webmaster@mydomain.com";
if (!preg_match("/^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,6})$/",$from))
{
echo "not a valid email address";
exit;
}
mail($to,'web contact form',$message,"From: $from\n");
?>
$from =$_POST[from_address'];
$message=$_POST['message'];
$to = "webmaster@mydomain.com";
if (!preg_match("/^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,6})$/",$from))
{
echo "not a valid email address";
exit;
}
mail($to,'web contact form',$message,"From: $from\n");
?>
1 comment
Will load this this weekend..very helpful tool! Best,
Chris
Leave a Comment