电子邮件验证无法正常运作

时间:2016-06-07 08:57:36

标签: php email

我制作了一个人们可以输入电子邮件的表格。 问题是他们现在可以在字段中添加他们想要的所有内容,我希望他们只能输入有效的电子邮件。我在互联网上找到了这段代码。

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  $emailErr = "Invalid email format"; 
}

并在我的PHP邮件发送代码中实现它:

<?php

$email = $_POST['subscribefield'];

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  $emailErr = "Invalid email format"; 
}


$to = "test@hotmail.com";
$subject = "Abonee voor de nieuwsbrief";
$body = "$email \n Heeft zich aangemeld voor de nieuwsbrief";

mail($to, $subject, $body);

echo "your mail was sent";
?>

仍然无效。我做错了什么?

提前致谢,

凯文

3 个答案:

答案 0 :(得分:2)

如果电子邮件地址错误,则不应尝试发送。

$email = $_POST['subscribefield'];

if (!filter_var($email, FILTER_VALIDATE_EMAIL))
  {
  $emailErr = "Invalid email format";
  }
  else
  {
  $to = "test@hotmail.com";
  $subject = "Abonee voor de nieuwsbrief";
  $body = "$email \n Heeft zich aangemeld voor de nieuwsbrief";
  mail($to, $subject, $body);
  echo "your mail was sent";
  }

?>

答案 1 :(得分:1)

您没有输出错误。 尝试这样的事情:

    if (filter_var('test@hotmail.com', FILTER_VALIDATE_EMAIL)) { 
        echo 'VALID'; 
    //Do you email send stuff

    } else {
        echo 'NOT VALID';
    //Display the error and don't send the mail
    }

答案 2 :(得分:1)

你没有任何可以检查$ emailErr的if语句。 如:

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  $emailErr = "Invalid email format"; 
}

if( isset($emailErr) === FALSE )
{
    $to = "test@hotmail.com";
    $subject = "Abonee voor de nieuwsbrief";
    $body = "$email \n Heeft zich aangemeld voor de nieuwsbrief";

    mail($to, $subject, $body);

    echo "your mail was sent";
}

或者只是

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  echo "Invalid email format";
  die();
}