filter_var() input validation by PHP

I recently discovered a very useful function in PHP. It‘s called filter_var(). It takes three arguments: a variable and the filter and a last optional argument, the options. The last argument uses an associative array of flags/options or a single flag/option. 

filter_var(variable, filter, options);

I use it in addition to javascript validation. That way when javascript is disabled your web-application is still secure and no unwanted data enters your precious database. I mainly use the filters :

FILTER_SANITIZE_NUMBER_INT

 FILTER_SANITIZE_STRING

FILTER_SANITIZE_EMAIL

FILTER_VALIDATE_EMAIL

FILTER_VALIDATE_INT.

The sanitize filters clear out any not wanted characters from a variable and the validate filters check wether the variable is well formed. for example when a user inputs an email address like this: user)’@user.com the sanitize filter FILTER_SANITIZE_EMAIL will clear out the ) and ’ characters. When you use the FILTER_VALIDATE_EMAIL filter it will return FALSE if given a not well formed email.   

Php filters

 

filter nameDescription
FILTER_CALLBACK Call a user-defined function to filter data
FILTER_SANITIZE_STRING Strip tags, optionally strip or encode special characters
FILTER_SANITIZE_STRIPPED Alias of “string” filter
FILTER_SANITIZE_ENCODED URL-encode string, optionally strip or encode special characters
FILTER_SANITIZE_SPECIAL_CHARS HTML-escape ’”<>& and characters with ASCII value less than 32
FILTER_SANITIZE_EMAIL Remove all characters, except letters, digits and !#$%&’*+-/=?^_`~@.[]
FILTER_SANITIZE_URL Remove all characters, except letters, digits and $-_.+!*’(),{}|\\^~[]`<>#%”;/?:@&=
FILTER_SANITIZE_NUMBER_INT Remove all characters, except digits and +-
FILTER_SANITIZE_NUMBER_FLOAT Remove all characters, except digits, +- and optionally .,eE
FILTER_SANITIZE_MAGIC_QUOTES Apply addslashes()
FILTER_UNSAFE_RAW Do nothing, optionally strip or encode special characters
FILTER_VALIDATE_INT Validate value as integer, optionally from the specified range
FILTER_VALIDATE_BOOLEAN Return TRUE for “1”, “true”, “on” and “yes”, FALSE for “0”, “false”, “off”, “no”, and ””, NULL otherwise
FILTER_VALIDATE_FLOAT Validate value as float
FILTER_VALIDATE_REGEXP Validate value against regexp, a Perl-compatible regular expression
FILTER_VALIDATE_URL Validate value as URL, optionally with required components
FILTER_VALIDATE_EMAIL Validate value as e-mail
FILTER_VALIDATE_IP Validate value as IP address, optionally only IPv4 or IPv6 or not from private or reserved ranges

This table comes from w3schools.com. For more extensive information on this function visit the w3schools website.

example

echo filter_var(’Test filter’, FILTER_SANITIZE_STRING);

Leave a comment