#native_company# #native_desc#
#native_cta#

PHP Filters: An Important Security Feature Page 2

By PHP Builder Staff
on October 1, 2009

The result of the code will echo “1122” because the variable type was found to be an integer. If the variable entered was “a344” nothing would be printed to the screen because the validation failed.
Ok, ok, i see you saying that is a pretty neat trick and all that. But there’s more. Lets say we want to make sure our variable is an integer and
has a value more than 5 and less than 10. How would we do that?
<?php

$variable = 6;
$minimum_value = 5;
$maximum_value = 10;

echo filter_var($variable, FILTER_VALIDATE_INT, array("options" => array("min_range"=>$minimum_value, "max_range"=>$maximum_value)));
?>
So, should the variable be within the limits–as it is in the above example–the number 6 will be echoed onto the screen.
PHP also provides a really good way of checking float values–especially useful for those of us who are building shopping carts and need to check that values have two decimal places. The example below will echo “31.53 is a valid floating point numer”.
<?php

$num = 31.53;

if(filter_var($num, FILTER_VALIDATE_FLOAT) === false)
{
	echo $num." is not valid!";
}
else
{
    echo $num." is a valid floating point number";
}

?>
Ever tried to validate a URL? If not, it’s best that you read RFC1738 – Uniform Resource Locators (URL) first, then open up your php text editor and write a class that basically describes the 2000 odd lines of text, right?

Well, no. Actually PHP can do this automatically with the URL filter.

<?php

$url = "http://www.somewebsite.domain";

if(filter_var($url, FILTER_VALIDATE_URL) === FALSE)
{
	echo $url." is not a valid URL<br />";
}
else
{
	echo  $url." is a valid URL<br />";
}

?>
“http://www.somewebsite.domain is a valid URL” is the response I get.
Now on to something that used to irritate me to no avail: email address validation. It’s one of these things you need to check against a regular
expression, right? Wrong. PHP’s FILTER_VALIDATE_EMAIL does that in a simple way, without even breaking a sweat. Here goes:
<?php

$email = "[email protected]";

if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
{
	echo $email." is invalid";
}
else
{
	echo $email." is valid";
}

?>
Now don’t you think that is worth it on its own? Email validation can be a major headache, especially for beginners, so in my opinion this is a little blessing in disguise.