停止发送电子邮件和成功消息

时间:2015-04-13 09:15:54

标签: php validation email

嗨,我是初学者和PHP。我在w3学校使用了这个验证示例......表单正在验证并正确发送邮件。然而。如果我按提交而不填写任何内容。它仍然发送一封空电子邮件。除非所有字段都填满,否则如何防止它不发送电子邮件...还有如何验证所有内容后如何显示感谢信息。我是非常新的PHP。如果你们可以复制我的代码并弄乱它,那就太好了。这样我就可以复制粘贴。

邮寄到功能代码:     

$message = "
<html>
<head>
<title>HTML email</title>
</head>
<body>
<p>This email contains HTML Tags!</p>
<table>
<tr>
<th>Firstname:</th>
<th>Email:</th>
<th>Interest:</th>
<th>comment:</th>
</tr>
<tr>
<td>$name</td>
<td>$email</td>
<td>$int</td>
<td>$comment</td>
</tr>
</table>
</body>
</html>
";
?>


<?php
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

// More headers
$headers .= 'From: <webmaster@example.com>' . "\r\n";
$headers .= 'Cc: myboss@example.com' . "\r\n";

mail($to,$subject,$message,$headers);
?>

验证码:

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $intErr = "";
$name = $email = $gender = $comment = $int = "";

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["email"])) {
     $emailErr = "Email is required";
   } else {
     $email = test_input($_POST["email"]);
     // check if e-mail address is well-formed
     if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
       $emailErr = "Invalid email format"; 
     }
   }

   if (empty($_POST["int"])) {
     $intErr = "Interest is required";
   } else {
     $int = test_input($_POST["int"]);
     // check if name only contains letters and whitespace
     if (!preg_match("/^[a-zA-Z ]*$/",$int)) {
       $intErr = "Only letters and white space allowed"; 
     }
   }

   if (empty($_POST["comment"])) {
     $comment = "";
   } else {
     $comment = test_input($_POST["comment"]);
   }

   if (empty($_POST["gender"])) {
     $genderErr = "Gender is required";
   } else {
     $gender = test_input($_POST["gender"]);
   }
}

function test_input($data) {
   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;
}
?>

2 个答案:

答案 0 :(得分:0)

首先,我建议你使用javascript在客户端进行表单验证,而不是在服务器端。它可以帮助服务器承受更少的负载。您可以在Google上搜索如何在提交前使用javascript验证表单。

如果您仍希望在服务器端执行此操作,那么当您找到空字段时,您只需使用&#34; Header&#34;将用户重定向到表单页面,显示空字段并询问它们再次填补它。 (您可以再次看到Javascript的重要性,它会为用户节省他/她等待服务器响应的时间)。

header("Location:Your-FormFile-Name");       

只有当所有内容都填满而非空时,才使用邮件功能。

答案 1 :(得分:0)

: - )

你好两个页面代码中的伙伴看起来很好。但没有关系。

如果没有表单标记,则不会提交您的html表单。并且验证代码文件不在html页面中调用。当您刷新页面时,邮件会自动进入。

请查看此链接,这有助于您.. http://www.formget.com/jquery-login-form/