1

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

1

1 Answer 1

4

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';
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

#Saty, strange, with example of 3 mails it works but with my real mail lists it doesnt.. I started circleing..
can you please post the value of $_POST['maillist']!!
I added the sample I am testing with.. it consists wrong and correct formatted mails
#Saty did you test it?
check edit use trim() in if(!filter_var(trim($mail), FILTER_VALIDATE_EMAIL)) { It will give you desire result.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.