Reputation: 952
I have the following script that checks emails and do something with them if they are correct formatted.. I am using FILTER_VALIDATE_EMAIL
for this
Here is the code:
if(!empty($_POST['maillist'])){
$_POST['maillist'] = '[email protected],
[email protected],[email protected],';
$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';
}
}
}
As you can see mails are formatted as mails but the function prints only first mail as correct and the rest as wrong.. Why is that? What am I missing? Thanks
Upvotes: 1
Views: 66
Reputation: 22532
Problem is with last comma in your email address. It create and empty value at the end . To avoid this you use isset()
if (!empty($_POST['maillist'])) {
$_POST['maillist'] = '[email protected],[email protected],[email protected],';
$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';
}
}
}
}
Upvotes: 4