Sanitizing and validating data

Still working on a project I found the typical login form.

This time the login credentials are the user’s email and a password. As always I found myself facing the task of validating an email. I had some php functions to do so but since they were almost a year old I decided to search for a more powerful already working solution.

To my surprise I found some very interesting info about email’s validation that I was unaware.

Some stuff that caught my eyes was that the email RFC actually allows the use of special characters on an email. The followin email is valid:


Noticed the quoted string? what about the escaped @?

In fact the following characters are valid on an email username: !#$%&’*+-/=?^_`{|}~@.[]

Wow! I bet that most of us didn’t knew that, and what’s worst most javascript or PHP validation functions won’t validate with the proper RFC rules. Deep trouble!

The good news are that PHP as of version 5 provides some functions that would help us deal with this problem.

Read the manual and search for filters, you’ll find a couple of very interesting and helpful functions to sanitize and validate data.

As for the email the following gets the job done:

$sanitized_email = filter_var($email,FILTER_SANITIZE_EMAIL);

$valid_email = filter_var($sanitized_email,FILTER_VALIDATE_EMAIL);


echo “Valid email!”;


It’s indeed a very helpful and concise way of validating data. The only bad thing is that it only works on PHP 5 or later. Nevertheless you’ll find some very powerful scripts on the links previously provided.

Hope this helps you as much as it helped me.


Comments are closed.