A blend of programming and seo

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).

contact How to secure a web contact form
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");

?>

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");
?>
Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay
  • Reddit
  • Twitter
  • HackerNews
  • StumbleUpon
  • Technorati

1 comment

1 Collegiate Chris { 04.20.09 at 1:04 pm }

Will load this this weekend..very helpful tool! Best,
Chris

Leave a Comment