php集成函数表单邮件验证不起作用FILTER_VALIDATE_EMAIL

时间:2015-08-24 08:38:49

标签: php

我有以下脚本检查电子邮件并在格式正确的情况下对它们执行某些操作。我正在使用FILTER_VALIDATE_EMAIL 这是代码:

if(!empty($_POST['maillist'])){
    $_POST['maillist'] = 'mariatettamanti@gmail.com,
H0889@sofiaertel.com,sdfd@sfs.com,';    

$mails = explode(',',$_POST['maillist']);

foreach($mails as $mail){
if(!filter_var($mail, FILTER_VALIDATE_EMAIL)) {
 echo $emailErr = $mail." - Invalid email format<br />"; 
}else{
echo 'do job with this mail';
}

}
}

正如您所看到的那样,邮件被格式化为邮件,但该功能仅打印第一封邮件为正确,其余邮件为错误。为什么会这样?我错过了什么?感谢

1 个答案:

答案 0 :(得分:4)

问题在于您的电子邮件地址中的最后一个逗号。它最终创造并清空价值。为避免这种情况,请使用isset()

if (!empty($_POST['maillist'])) {
    $_POST['maillist'] = 'H0889@sofisadatel.com,info@daddsadyomiaasdmi.com,info@hotsdaelmidasami.com,';
    $mails = explode(',', $_POST['maillist']);

    foreach ($mails as $mail) {
        if (isset($mail) && $mail != "") {// check for empty email
           if(!filter_var(trim($mail), FILTER_VALIDATE_EMAIL)) {
                echo $emailErr = $mail . " - Invalid email format<br />";
            } else {
                echo 'do job with this mail';
            }
        }
    }
}