php - 更专业的错误处理

标签 php email error-handling

我有一个联系表,并且通过使用“if”语句逐一检查每个字段来处理错误。我觉得很难,我似乎找不到更好/更有效的方式来使他们工作。如果一个(或多个)为真,我也希望标题显示“错误”。但是我无法让它们与单独的“if”语句一起使用。

这是我的代码:

$name = $_POST['name']; //get data from the form
$email = $_POST['email'];//get data from the form
$message = $_POST['message'];//get data from the form
if($name == ""){
echo"<p class='error'>Please enter a name.</p>";
}
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$",$email)){
echo "<p class='error'>Your email address is not valid.</p>"; 
}
if($message == ""){
echo"<p class='error'>Please enter a message.</p>";
}
else{
echo"all ok, send email code...";   
}

编辑:这些错误是用于窗体的验证。

最佳答案

But I cant get them to work with the separate "if" statements.



只是将错误存储在变量中
$error = array();

if($name == ""){
  $error[] = "Please enter a name.";
}
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$",$email)){
  $error[] = "Your email address is not valid."; 
}
if($message == ""){
 $error[] = "Please enter a message.";
}

if (!$error) {
  // do not echo anything here
  // but send an email
  // and use header("Location:") to redirect a user to thanks page
} else {
  echo "Error";
  foreach ($error as $line) {
    echo "<p class='error'>$line</p>";
  }
}

关于php - 更专业的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3816312/

相关文章:

php - 尝试获取登录错误消息/验证以在登录表单上工作?

php - MAC 的 SMTP 服务器 - 有什么建议吗?

authentication - 登录失败 : unknown user name or bad password

java - IllegalAccessError 和 IllegalAccessException 的区别

python-3.x - 如何错误检查 urllib.request

php - 在没有 php.ini 的情况下设置 display_errors=0 和 log_errors=1

php - 从 MYSQL 数据库中选择按天分组的记录

php - 使用ajax将数组发布到PHP

php - 使用 Zend Framework 阅读 gmail

ios - 我可以防止 iOS 关闭电子邮件撰写窗口,丢失用户数据吗