像这样解决它:
<form id="form" method="post" name="mailform" action="mail.php" onsubmit="mail(); return false;">
<p>
<label for='name'>Stuff</label><br>
<input type="text" name="stuff">
</p>
<input type="submit" name="submit" value="Send">
</form>
<p id="result" style="display: none">
<img src="images/succes.png"><br>
Thank you
</p>
/*----------------------------*/
function mail() {
var form = document.getElementById("form");
var name = form.name.value;
var email = form.email.value;
var phone = form.phone.value;
var message = form.message.value;
var valid = true;
if (!name) {form.name.style.backgroundColor = '#FF9481'; valid = false; }
else {form.name.style.backgroundColor = '';}
if (!email && !phone) {form.email.style.backgroundColor = '#FF9481'; form.phone.style.backgroundColor = '#FF9481'; valid = false;}
else {form.email.style.backgroundColor = ''; form.phone.style.backgroundColor = '';}
if (!message) {form.message.style.backgroundColor = '#FF9481'; valid = false;}
else {form.message.style.backgroundColor = '';}
if (email) {
var patt=/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/gi;
var result=patt.test(email);
if (!result) {form.email.style.backgroundColor = '#FF9481'; valid = false;}
else form.email.style.backgroundColor = '';
}
if (phone) {
var patt=/[^0-9|\-| ]/g;
var result=patt.test(phone);
if (result) {form.phone.style.backgroundColor = '#FF9481'; valid = false;}
else form.phone.style.backgroundColor = '';
}
if (!valid) return false;
var datastr = 'name='+ name + '&email=' + email + '&phone=' + phone + '&message=' + message;
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if (xmlhttp.responseText == "ok") {
form.style.display = 'none';
document.getElementById("result").style.display = '';
}
else {
form.message.value= "That doesn't seem right";
}
}
}
xmlhttp.open("GET","mail.php?" + datastr,true);
xmlhttp.send();
}
/*----------------------------*/
<?php
$name = $_GET['name'];
$etc...
if(IsInjected($name)||IsInjected($visitor_email)||IsInjected($phone)||IsInjected($message))
{
echo "Something fishy going on?";
exit;
}
[...]
mail($to,$email_subject,$email_body,$headers);
echo "ok";
function IsInjected($str)
{
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str))
{
return true;
}
else
{
return false;
}
}
?>