Wednesday, December 19, 2007

PHP filters

Gone are days of writing a validation class for vaildating different user inputs.
Gone are days of writing secure functions for validating URL, email address,etc.
In october 2005, first version of Filter package was released by PECL and within 1 year and 5 more releases PECL released final version 0.11 of Filter pack
age.

You can download filter package from here http://pecl.php.net/package/filter.
All you need is Php5.0 or higher and PEAR installer.
Installation steps are simple just write this in your console
$ pecl install filter

Usage Documentation.
Although filter functions are documented in php.net (http://in.php.net/filter), I find these documentation incomplete.
While doing some googling I found a good link which described different usages of Filter functions in a simple manner.
The Link is : http://phpro.org/tutorials/Filtering-Data-with-PHP.html

I won't provide you with entire usage as it would be a waste of time when I already have good link doing the same for me.
I will only provide a snapshot to show you the power of PHP filters

Filter IP Address

Following on from validation of URLs, we often find we need to validate an IP Address. Of course, and IP address may be of different formats for ipv4 and ipv6. An IP address may also need to be within a range of private or reserved ranges. The filter extension makes it possible to discern these differences and to validate an IP address to fit most needs. In its simplest form the validation of a url will look like this.



/*** an IP address ***/
$ip = "192.168.0.1";

if(
filter_var($ip, FILTER_VALIDATE_IP) === FALSE)
{
echo
"$ip is not a valid IP";
}
else
{
echo
"$ip is valid";
}
?>

As we have supplied the above with a valid IP address it validates and all is well. But now we may wish to validate an IPV6 address or an address with a private range. The IP filter has several flag with which to validate an IP address with. Listed here.

  • FILTER_FLAG_IPV4
  • FILTER_FLAG_IPV6
  • FILTER_FLAG_NO_PRIV_RANGE
  • FILTER_FLAG_NO_RES_RANGE

Starting at the top we will check to see if an IP is a valid IPV4 address.



/*** an IP address ***/
$ip = "192.168.0";

/*** try to validate as IPV4 address ***/
if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === FALSE)
{
echo
"$ip is not a valid IP";
}
else
{
echo
"$ip is valid";
}
?>

In the above example the IP address has failed to validate as it is not a complete IPV4 address. It would need to be of the form of the example that preceded it, 192.168.0.1 to validate. This is fine, but growth of the net has seen us run out of IPV4 addresses and so we need to validate against IPV6 addresses also.


Please visit the above link, read carefully and start saving time by using the above