Here is my final draft (I hope it is at least), because I am tired of messing with it! I am pretty confidant that it covers all of the important security threats. Feel free to use it, because I'm pretty sure it's an awesome script. Please let me know if you see any security holes or potential problems with it. Thanks! <?php
$mailto = 'youremail@gmail.com' ;
$from = "yourdomain.com Formmail" ;
$formurl = "http://www.yourdomain.com/formmail.php" ;
$errorurl = "http://www.yourdomain.com/formmailerror.php" ;
$thankyouurl = "http://www.yourdomain.com/thankyou.php" ;
function remove_headers($string) {
$headers = array(
"/to\:/i",
"/from\:/i",
"/bcc\:/i",
"/cc\:/i",
"/Content\-Transfer\-Encoding\:/i",
"/Content\-Type\:/i",
"/Mime\-Version\:/i"
);
if (preg_replace($headers, '', $string) == $string) {
return $string;
} else {
die('You think Im spammy? Spammy how? Spammy like a clown, spammy?');
}
}
$uself = 0;
$headersep = (!isset( $uself ) ¦¦ ($uself == 0)) ? "\r\n" : "\n" ;
$name = remove_headers($_POST['name']);
$email = remove_headers($_POST['email']);
$subject = remove_headers($_POST['subject']);
$comments = remove_headers($_POST['comments']);
$http_referrer = getenv( "HTTP_REFERER" );
if (!isset($_POST['email'])) {
header( "Location: $errorurl" );
exit ;
}
if (!preg_match("/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i",$email)) {
header( "Location: $errorurl" );
exit ;
}
if (empty($name) ¦¦ empty($email) ¦¦ empty($subject) ¦¦empty($comments)) {
header( "Location: $errorurl" );
exit ;
}
if ( ereg( "[\r\n]", $name ) ¦¦ ereg( "[\r\n]", $email ) ) {
header( "Location: $errorurl" );
exit ;
}
if (get_magic_quotes_gpc()) {
$comments = stripslashes( $comments );
}
if (strlen($comments) > 1250) {
$comments=substr($comments, 0, 1250).'...';
}
$message =
"This message was sent from:\n" .
"$http_referrer\n\n" .
"Name: $name\n\n" .
"Email: $email\n\n" .
"Subject: $subject\n\n" .
"comments: $comments\n\n" .
"\n\n------------------------------------------------------------\n" ;
mail($mailto, $from, $message,
"From: \"$name\" <$email>" . $headersep . "Reply-To: \"$name\" <$email>" . $headersep );
header( "Location: $thankyouurl" );
exit ;
?>