View Single Post
Old 01-07-2013, 02:49 PM   PM User | #3
codernoob
New Coder

 
Join Date: Sep 2012
Posts: 26
Thanks: 17
Thanked 0 Times in 0 Posts
codernoob is an unknown quantity at this point
I have made some changes to the code, can someone check and let me know if the changes i have made are good enough - atleast to a good extend - to stop xss attacks?

Code:
<?php
$title = $_POST['title'];
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$dodgy_strings = array(
                "content-type:"
                ,"mime-version:"
                ,"multipart/mixed"
                ,"bcc:"
);

function is_valid_email($email) {
  return preg_match('#^[a-z0-9.!\#$%&\'*+-/=?^_`{|}~]+@([0-9.]+|([^\s]+\.+[a-z]{2,6}))$#si', $email);
}

function contains_bad_str($str_to_test) {
  $bad_strings = array(
                "content-type:"
                ,"mime-version:"
                ,"multipart/mixed"
		,"Content-Transfer-Encoding:"
                ,"bcc:"
		,"cc:"
		,"to:"
  );
  
  foreach($bad_strings as $bad_string) {
    if(eregi($bad_string, strtolower($str_to_test))) {
      echo "$bad_string found. Suspected injection attempt - mail not being sent.";
      exit;
    }
  }
}

function contains_newlines($str_to_test) {
   if(preg_match("/(%0A|%0D|\\n+|\\r+)/i", $str_to_test) != 0) {
     echo "newline found in $str_to_test. Suspected injection attempt - mail not being sent.";
     exit;
   }
} 

if($_SERVER['REQUEST_METHOD'] != "POST"){
   echo("Unauthorized attempt to access page.");
   exit;
}

if (!is_valid_email($email)) {
  echo 'Invalid email submitted - mail not being sent.';
  exit;
}

contains_bad_str($email);
contains_bad_str($name);
contains_bad_str($phone);
contains_bad_str($message);

contains_newlines($email);
contains_newlines($subject);

$formcontent=" From: \n $title $name \n Email: $email \n Phone: $phone \n Message: $message";
$mailheader = "From: $email \r\n";
$recipient = "queries@xyz.com";
$subject = "Contact Form";
mail($recipient, $subject, $formcontent, $mailheader);
if (isset($_POST['email'])) {
header('Location:thanks.html');
}
?>
codernoob is offline   Reply With Quote