Tuesday, 6 March 2012

Validating an email address in PHP

Just a little post, because most of the top Google results point to old pages that aren't correct.

Basically, I wanted to validate some input to see if it was a valid email address. Rather than rely on a regular expression, I knew there was a better way of doing it. In PHP at least.

So, the function you're looking for is filter_var(). If you're doing it with $_POST or $_GET you can instead use filter_input().

In my case, it's verifying that an API is providing me with a valid email, as somebody at the other end likes to chuck in "unsubscribed" to the email field. So the code looks similar to this.

if (false === filter_var($valueToCheck, FILTER_VALIDATE_EMAIL) ) {
    // This is *not* an email address
} else {
   // This *is* an email address
}

No comments:

Post a Comment