Last Updated: February 25, 2016
·
440
· samuelm

Filter and validate your variables effectively

I recently discover that many php developers doesn't know this function .
Since PHP5 a very effective way to filter your variables is to use the filter_var function http://php.net/manual/en/function.filter-var.php

exemple :

// Returns TRUE for "1", "true", "on" and "yes". Returns FALSE otherwise.
$res = filter_var($foo, FILTER_VALIDATE_BOOLEAN);

// Validates value as float.
$res = filter_var($foo, FILTER_VALIDATE_FLOAT);

// Validates value as INT.
$res = filter_var($foo, FILTER_VALIDATE_INT);

You also validate type like email , url or ip

 // Validates value as e-mail.
$res = filter_var("mail@domain.ltd", FILTER_VALIDATE_EMAIL);    

Very usefull .