Webshop Blog
PHP Filters and How to Use Them
PHP really shows its true colors when it comes to how easy it is to learn–especially for new programmers. However, as result of this new coders often overlook a lot of really useful functionality that PHP has to offer, particularly when it comes to securing our scripts. Today we’re going to take a look at PHP filters and how easy it is to use them to increase our script’s security.
What Are PHP Filters?
If you have ever written any script that has been in public use, you should know to never trust the user, PHP filters step in to help solve this problem. PHP filters are implemented through the PHP Filter Extension. The Filter Extension is a rather thorough library of pre-defined rules you can use to clean user input and prepare data for database storage or any number of other implementations you may come across.
How Do PHP Filters Work?
PHP filters work through a couple of built-in functions, namely filter_var() and filter_var_array(), and flags you pass to these methods. The flag you pass these functions will determine which filter you want to implement.
There are two types of filters, validation and sanitization filters. Validation filters are similar to a true/false type check. When using a validation filter, the function will return the original data you passed it if the data passed the validation check. When using sanitization filters, the function will return the data you passed it after it removes the necessary data to make it pass the test.
To see what filters are supported in your environment, there is a nifty function filter_list(). Example:
print_r(filter_list());
//prints...
Array
(
[0] => int
[1] => boolean
[2] => float
[3] => validate_regexp
[4] => validate_url
[5] => validate_email
[6] => validate_ip
[7] => string
[8] => stripped
[9] => encoded
[10] => special_chars
[11] => unsafe_raw
[12] => email
[13] => url
[14] => number_int
[15] => number_float
[16] => magic_quotes
[17] => callback
)
These are the filters that are supported on my server, yours may be different. We’re going to take a look at a few examples of what you can do with these filters.
If you would like more information on the filter_var() and filter_var_array() functions, check out the PHP manual entries for these functions for more information about them specifically: filter_var(), filter_var_array().
Useful PHP Validation Filters
Validating Integers
You can validate integer with the FILTER_VALIDATE_INT flag. If you pass the function an integer, it will return it just like it came. However, if you pass it say, a string or a float data type it will return NULL or FALSE.
$var = 473; filter_var($var, FILTER_VALIDATE_INT); //returns 473 $var = 'hello'; filter_var($var, FILTER_VALIDATE_INT); //returns FALSE $var = 71.4; filter_var($var, FILTER_VALIDATE_INT); //returns FALSE
You can also specify options for the FILTER_VALIDATE_INT flag, like min, max and default values. You have to be careful when defining the $options array, notice that its a multidimensional array.
$var_1 = 73;
$var_2 = 246;
$options = array(
'options' => array(
'default' => 3,
'min_range' => 0,
'max_range' => 99,
)
);
filter_var($var_1, FILTER_VALIDATE_INT, $options); //returns 73
filter_var($var_2, FILTER_VALIDATE_INT, $options); //returns 3
Notice that the second filter_var() call returned 3, this is because of the default value we defined in the $options array.
Validating Floats
Validating a FLOAT work just like validating an INT does, but it uses the FILTER_VALIDATE_FLOAT flag instead.
$var_1 = 45.3; $var_2 = 246; filter_var($var_1, FILTER_VALIDATE_FLOAT, $options); //returns 45.3 filter_var($var_2, FILTER_VALIDATE_FLOAT, $options); //returns 246
Note that if you pass an integer into this function with the FILTER_VALIDATE_FLOAT flag, it will still return it as if it was a float.
Validating E-mail Addresses
You can also use this method for validating more abstract data types, such as e-mail addresses.
$var_1 = "jordan@17webshop.com"; $var_2 = "some data that is obviously not an e-mail address; filter_var($var_1, FILTER_VALIDATE_EMAIL); //returns jordan@17webshop.com filter_var($var_2, FILTER_VALIDATE_EMAIL); //returns FALSE
However, this method isn’t quite as good as a custom regex could be. An e-mail address like a@a.a, which is obviously invalid, still passes. The following regex would be a better solution:
$pattern = '/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/';
$email_1 = 'jordan@17webshop.com';
$email_2 = 'a@a.a';
preg_match($pattern, $email_1); // returns TRUE
preg_match($pattern, $email_2); //returns FALSE
Validating URLs
Validating URLs is typically pretty difficult, filter_var() however, does a pretty excellent job. What’s interesting about this flag is it optionally takes additional flags to facilitate better validation. Here’s a list of the additional, optional flags available:
FILTER_FLAG_SCHEME_REQUIREDFILTER_FLAG_HOST_REQUIREDFILTER_FLAG_PATH_REQUIREDFILTER_FLAG_QUERY_REQUIRED
Let’s look at a few examples:
$var_1 = 'http://www.17webshop.com'; $var_2 = 'http://www.17webshop.com/path/to/some/file'; $var_3 = 'http://www.17webshop.com/path/to/some/file/?foo=bar'; $var_4 = 'www.17webshop.com'; $var_5 = 'some_file.html'; $var_6 = "/path/to/some/file"; filter_var($var_1, FILTER_VALIDATE_URL); // returns http://www.17webshop.com filter_var($var_1, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED); // returns FALSE filter_var($var_2, FILTER_VALIDATE_URL); // returns http://www.17webshop.com/path/to/some/file filter_var($var_2, FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED); // returns FALSE filter_var($var_3, FILTER_VALIDATE_URL); // returns http://www.17webshop.com/path/to/some/file/?foo=bar filter_var($var_4, FILTER_VALIDATE_URL); // returns FALSE filter_var($var_5, FILTER_VALIDATE_URL); // returns FALSE filter_var($var_6, FILTER_VALIDATE_URL); // returns FALSE
Validating IP Addresses
Validating IP Addresses is simple as well, and just like the FILTER_VALIDATE_URL flag, the FILTER_VALIDATE_IP flag allows a few optional flags in addition, they are listed below. You can even check ipv6 addresses.
FILTER_FLAG_IPV4FILTER_FLAG_IPV6FILTER_FLAG_NO_PRIV_RANGEFILTER_FLAG_NO_RES_RANGE
$var_1 = '192.168.0.1'; $var_2 = '543.152.3.9'; $var_3 = '3ffe:1900:4545:3:200:f8ff:fe21:67cf'; echo filter_var($var_1, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4); // returns 192.168.0.1 echo filter_var($var_2, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4); // returns FALSE echo filter_var($var_3, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6); // returns 3ffe:1900:4545:3:200:f8ff:fe21:67cf
Note that 543.152.3.9 returns false, this is because the IP address with the highest value that is still acceptable is 255.255.255.255.
The FILTER_FLAG_NO_PRIV_RANGE and FILTER_FLAG_NO_RES_RANGE check to see if the address is within a private, or reserved range respectively.
Useful PHP Sanitization Filters
Sanitizing a String
Sanitizing data is just as easy as validating it. Remember that sanitizing is different than validating because sanitizing removes unwanted characters and then returns the newly validated data. Let’s take a look at sanitizing some strings.
$var_1 = 'some string data '; $var_2 = '"some string data" '; filter_var($var_1, FILTER_SANITIZE_STRING); //returns some string data filter_var($var_2, FILTER_SANITIZE_STRING); //returns "some string data"
Sanitizing Integers
$var_1 = 123214; $var_2 = '213h34bh312'; filter_var($var_1, FILTER_SANITIZE_NUMBER_INT); //returns 123214 filter_var($var_2, FILTER_SANITIZE_NUMBER_INT); //returns 21334312
Filter Callback
Maybe one of the best things about the filter_var() function is the FILTER_CALLBACK flag as it allows you define your own rule via a callback function. If you can’t find a rule that meets your needs exactly, just define one yourself with this flag.
function my_rule($str) {
return str_replace(" ", "+", $str);
}
$var_1 = "some string data with spaces in it";
$options = array(
'options' => 'my_rule'
);
filter_var($var_1, FILTER_CALLBACK, $options); //returns some+string+data+with+spaces+in+it
Conclusion
Hopefully this post has taught you something you didn’t know about PHP, or jogged your memory on some useful functionality available to you. I didn’t go through every possible flag, for the sake of brevity, and because of the fact that while some of them are helpful and rather useful. Some of them, just… aren’t. If you want more information about these flags, take a look at the PHP manual entry.
As always, if you have any questions about anything discussed here. Feel free to leave them in the comments. I am always willing to help out.

Hopefully this post has taught you something you didn’t know about PHP, or jogged your memory on some useful functionality available to you. I didn’t go through every possible flag, for the sake of brevity, and because of the fact that while some of them are helpful and rather useful. Some of them, just… aren’t. If you want more information about these flags, take a look at the PHP manual entry.
As always, if you have any questions about anything discussed here. Feel free to leave them in the comments. I am always willing to help out.
This is a nice script.
It is easy to understand.
doing done good job..:-)
Thanks a lot..!
[...] This post was Twitted by suhd [...]
Pretty nice post. I just stumbled upon your blog and wanted to say that I have really enjoyed browsing your blog posts. In any case I’ll be subscribing to your feed and I hope you write again soon!
Interesting blog, the author thanks so much for the interesting explanation!
Keep it up, great success! Bloggy wish a lot of good posts!
I want to quote your post in my blog. It can?
And you et an account on Twitter?
[...] PHP Filters and How to Use Them [...]
[...] the original here: PHP Filters and How to Use Them | 17 Webshop | Web Design + … Share and [...]
[...] This post was Twitted by suhd [...]
@Gabriel
well, for validation the advantage is simply that it offers you a few more options, the min, max, and default values. However, the
FILTER_SANITIZE_NUMBER_INTflag would, in my opinion, be the best choice because it will strip out any non numeric characters from the value, leaving you with a clean integer.is_integer()will just return true/false, which may be all you need,(int)$foowill just convert it to an integer, which means truncation if its a float and a mess if its an alphabetical string. I don’t consider typecasting to be very reliable.Hi again. I Forgot “is_integer($foo)” in the examples.
Hi, nice blog!
I have a question: What are the advantages of using this methods instead of, for example for integer validation, “(int)$foo” or “intval($foo)”?
Thanks and sorry by my english.
@Web Trindade
No, sorry, I should have made that more clear. The filter extension is only available in PHP 5.
[...] rest is here: PHP Filters and How to Use Them | 17 Webshop | Web Design + … By admin | category: php scripts, scripts | tags: coders-often, how-easy, php, [...]
Very useful article / tutorial. Thanks!
Great!
Are filter avaliable in php4?
[...] the original post: PHP Filters and How to Use Them | 17 Webshop | Web Design + … [...]
[...] Read the original post: PHP Filters and How to Use Them | 17 Webshop | Web Design + … [...]