Archive for March, 2010

Sanitizing and validating data

Thursday, March 25th, 2010

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:

“jimmy”\@home@gmail.com

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);

if($valid_email!==false){

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.

When random ain’t that random

Wednesday, March 24th, 2010

Been working on a small project that demanded the use of captcha.

Since it’s very small I decided to create my own captcha class. Nothing very complicated but still enough to avoid most of the spam robots. Anyway In order to create a nice captcha mi code draws some lines whose x,y coordinates where randomly generated through PHP’s rand function.

Later that day as I was finishing a widget I came up with this cool site. It’s all about randomness so I started reading.

To my surprise I found out a specific page that talked about pseudo random numbers generators (PRNG) and true random numbers generators (TRNG). PHP’s rand function is a PRNG and it’s not as cool as I thought.

For what the page explains the rand function should be avoided for true random number generatiosn when on a Windows server. Apparently it behaves oddly and follows some sort of pattern. They recommend the use of mt_rand instead which generates a more random number and also is faster than rand!!!!

Obviously I moved to mt_rand.

Please read the article, you’ll be surprised!!!