Contactform在未填写必填字段时发送邮件

时间:2017-08-24 19:47:36

标签: php forms validation email

我想设置这样的联系表单,如果没有填写必填字段,将不会发送邮件。如果我点击提交'仍然有邮件发送。有人可以帮我解决它的好方向吗?我只希望在填写所有必填字段时发送邮件。

<?php


$nameErr = $emailErr = "";
$naam = $email = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["naam"])) {
    $nameErr = "Wij willen graag weten hoe u heet!";
  } else {
    $naam = test_input($_POST["naam"]);
  }

  if (empty($_POST["email"])) {
    $emailErr = "Zonder een mailadres kunnen wij uw mail niet beantwoorden";
  } else {
    $email = test_input($_POST["email"]);
  }

}

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

if(isset($_POST['submit']))
{
    $naam = $_POST['naam'];
    $email = $_POST['email'];
    $onderwerp ="Contactformulier ingevuld door $naam";
    $bericht = $_POST['bericht'];
    $CS = "google@gmail.com";
    $afzender = "Googla BV";

    $headers = 'From: GoogleBV <no-reply@google.nl>' . "\r\n" .
    'Reply-To: ' . $email . "\r\n" .
    'X-Mailer: PHP/' . phpversion();
    mail($CS, $onderwerp, $bericht, $headers);

}


 ?>

1 个答案:

答案 0 :(得分:0)

你应该这样做:

<?php


$nameErr = $emailErr = "";
$naam    = $email = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["naam"])) {
        $nameErr = "Wij willen graag weten hoe u heet!";
    } else {
        $naam = test_input($_POST["naam"]);
    }

    if (empty($_POST["email"])) {
        $emailErr = "Zonder een mailadres kunnen wij uw mail niet beantwoorden";
    } else {
        $email = test_input($_POST["email"]);
    }

}

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

if (isset($_POST['submit']) && !empty($_POST['email']) && !empty($_POST['naam'])) {
    $naam      = $_POST['naam'];
    $email     = $_POST['email'];
    $onderwerp = "Contactformulier ingevuld door $naam";
    $bericht   = $_POST['bericht'];
    $CS        = "google@gmail.com";
    $afzender  = "Googla BV";

    $headers = 'From: GoogleBV <no-reply@google.nl>' . "\r\n" . 'Reply-To: ' . $email . "\r\n" . 'X-Mailer: PHP/' . phpversion();
    mail($CS, $onderwerp, $bericht, $headers);

}


?>

现在它检查表单是否已提交且用户名/电子邮件是否为空。