固定的东西:
- 电子邮件验证。(重要的)
- 不打印空 $vars
- $headers 正确分隔
代码:
//shamelessly stolen from http://www.linuxjournal.com/article/9585?page=0,3
function validEmail($email)
{
$isValid = true;
$atIndex = strrpos($email, "@");
if (is_bool($atIndex) && !$atIndex)
{
$isValid = false;
}
else
{
$domain = substr($email, $atIndex+1);
$local = substr($email, 0, $atIndex);
$localLen = strlen($local);
$domainLen = strlen($domain);
if ($localLen < 1 || $localLen > 64)
{
// local part length exceeded
$isValid = false;
}
else if ($domainLen < 1 || $domainLen > 255)
{
// domain part length exceeded
$isValid = false;
}
else if ($local[0] == '.' || $local[$localLen-1] == '.')
{
// local part starts or ends with '.'
$isValid = false;
}
else if (preg_match('/\\.\\./', $local))
{
// local part has two consecutive dots
$isValid = false;
}
else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
{
// character not valid in domain part
$isValid = false;
}
else if (preg_match('/\\.\\./', $domain))
{
// domain part has two consecutive dots
$isValid = false;
}
else if
(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
str_replace("\\\\","",$local)))
{
// character not valid in local part unless
// local part is quoted
if (!preg_match('/^"(\\\\"|[^"])+"$/',
str_replace("\\\\","",$local)))
{
$isValid = false;
}
}
if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
{
// domain not found in DNS
$isValid = false;
}
}
return $isValid;
}
$destination = "handle@domain.com";
$email_from = $_POST['Email'];
if (!validEmail($email_from))
die("Invalid email address");
$message = "<html>
<body style=\"font-family:Arial; font-size:10pt;\">
Hello,<br>
You have recieved an online form submission:<br><br>
<table width='600' border='1' cellspacing='3'>";
//Gather posted variables:
foreach($_POST as $keys => $vars){
if (empty($vars)) continue; #skip if vars is empty
$message .= "<tr>
<td bgcolor='#CCCCCC'><b>$keys:</b></td> <td><b><font color='red'>$vars</font></b></td>
</tr>";
}
$message = str_replace("_"," ", $message);
$message .= "
</table>
</body>
</html>
";
#separating headers properly
$headers = "From: $email_from\r\n".
'Reply-To: '.$email_from."\r\n".
"Content-Type: text/html; charset=\"utf-8\"\r\n".
"Content-Transfer-Encoding: 7bit\r\n".
"MIME-Version: 1.0\n";
mail($destination,"Online Form Submission",$message,$headers);
echo "Thank you for your submission!";
?>