我遇到了一个问题,我已成功验证表单中的输入和必填字段。但是如果用户提交表单,不管字段是否为空;它显示带有字段的错误消息,但也发送空电子邮件。
我相信只需要做一个简单的调整。但我迷路了。请查看我拥有的以下代码:
<?php
$nameErr = $snameErr = $emailErr = $ownerNameErr = $ownerNatErr = $genderErr = $websiteErr = "";
$name = $sname = $regAddress = $email = $gender = $comment = $ownerName = $ownerNat = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["sname"]))
{$snameErr = "Company Second Name is required";}
else
{
$sname = test_input($_POST["sname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$sname))
{
$snameErr = "Only letters and white space allowed";
}
}
extract($_POST);
$to="example@example.com";
$subject="Subject";
$body="<table width='100%' cellspacing='10' cellpadding='0'>
<tr>
<td style='color:blue;font-weight:bold;margin-left:500px;font-size:20px;' colspan='3'>My Form</td>
</tr>
<tr>
<td>Name</td>
<td>:</td>
<td>$name</td>
</tr>
<tr>
<td>Second Choice</td>
<td>:</td>
<td>$sname</td>
</tr>
</table>";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: MySite '."\r\n";
/*$headers .= 'Reply-To:'."$textfield5"."\r\n";*/
if(mail($to,$subject,$body,$headers))
{
$msg = "Thank you for contacting us. We will get back to you soon.";
/*$msg= "Successfully Sent";*/
}
else
{
$msg= "msg not sent";
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
HTML 部分
<span class="error">* <?php echo $ownerNatErr;?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
input type="submit" name="submit" value="Submit Information">
非常感谢任何帮助/建议。
问候。