Wednesday 21 March 2012

Beware easy shortcuts

If you need to replace a character, make sure you replace it with the correct character!

I recently made the mistake of replacing a comma (,) with , That isn't the correct ascii character. , is.

And because I do my IE testing last, I didn't pick it up. Just thought it'd be a good heads up for anyone who didn't realise it either.

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
}