Using Filters in PHP 5

You’ve probably built custom functions and libraries to validate user input in PHP 5. There’s an easier way to do this, and it can save you considerable time and effort. It involves using PHP 5’s own built-in and often-neglected filters. This nine-part series will introduce you to their use.

Definitely, one of the most common tasks that PHP programmers have to tackle during the development of web applications is validating user-supplied data. This fact brings up a crucial and mandatory rule: the client side is always non-trusted terrain with little or no control. Consequently, any data coming from it needs to be properly filtered and thoroughly checked before doing something useful with it.

Fortunately, the introspective capabilities offered by PHP allow you to check incoming data in a pretty straightforward way. It comes packaged with a number of native functions, which you’ve surely used hundreds of times before, that permit you to verify different data types very easily. These data types include strings and float numbers, integers, arrays and objects. This neat set of functions, along with some extra features bundled exclusively with PHP 5, such as type hinting, allow developers build libraries that can be used for checking empty strings and numeric ranges, email addresses and URLs, and so forth.

Purely aside from these other developer-built libraries, however, PHP 5 also includes by default a useful library that allows you to perform all of these types of validation tasks by means of a bunch of native filters. Yes, these rather overlooked filters will let you check for integers and float numbers, URLs, email addresses, etc., even more easily than by using your own custom functions. Best of all, they don’t require any additional configuration.

Indeed, the use of native PHP filters may contribute significantly to saving time and effort when it comes to validating input data. In this series of articles I’m going to attempt to provide you with a concise guide to how to use them, as usual by way of a decent variety of code samples.

So, now that that you know what to expect from this group of articles, it’s time to move forward and start discovering the real power that stands behind using filters in PHP 5. Let’s begin now!

{mospagebreak title=Filters available in PHP 5}

Before I start explaining how to use filters in PHP 5, it’s convenient to check which of them comes with the PHP distribution. To do this, I’m going to use a pair of handy native functions called “filter_list()” and “filter_id()." The first one will return an array of the existing filters and the second one will retrieve their corresponding IDs.

A simple demonstration of how to use these functions is coded below. Take a look at the following example:

<?php

 

// example on using the ‘filter_list()’ function

foreach(filter_list() as $id => $filter)

{

echo ‘<p> Filter Name: ‘ . $filter . ‘ ————- Filter ID: ‘ . filter_id($filter) . ‘</p><hr />';

}

 

/* displays the following

 

Filter Name: int ————- Filter ID: 257

 

Filter Name: boolean ————- Filter ID: 258

 

Filter Name: float ————- Filter ID: 259

 

Filter Name: validate_regexp ————- Filter ID: 272

 

Filter Name: validate_url ————- Filter ID: 273

 

Filter Name: validate_email ————- Filter ID: 274

 

Filter Name: validate_ip ————- Filter ID: 275

 

Filter Name: string ————- Filter ID: 513

 

Filter Name: stripped ————- Filter ID: 513

 

Filter Name: encoded ————- Filter ID: 514

 

Filter Name: special_chars ————- Filter ID: 515

 

Filter Name: unsafe_raw ————- Filter ID: 516

 

Filter Name: email ————- Filter ID: 517

 

Filter Name: url ————- Filter ID: 518

 

Filter Name: number_int ————- Filter ID: 519

 

Filter Name: number_float ————- Filter ID: 520

 

Filter Name: magic_quotes ————- Filter ID: 521

 

Filter Name: callback ————- Filter ID: 1024

*/

?>

As you can see in the above code sample, the combined use of the “filter_list()” and “filter_id()” functions provides useful information about the filters that are available with the PHP 5 distribution. In this particular case, the name and ID of each filter is displayed on screen via a simple “foreach” construct, which helps you understand each one’s functionality. 

Of course, from the previous example it’s easy to see that there are filters available for checking integers and float numbers, Boolean values and regular expressions, URLs, email and IP addresses, strings and special characters, and so forth. However, since this will be a progressive process, I’m going to discuss  each filter in detail in successive tutorials of this series.

At this point you should have some idea of how useful PHP 5 filters can really be for validating incoming data. Therefore, it’s time to start an in-depth discussion of the first filter shown by the previous list. It is the one responsible for checking whether a given value is an integer.

This brand new PHP 5 filter will be explored in detail in the next segment. Thus, to learn how to work with it, click on the link below and read the next few lines.

{mospagebreak title=Checking for integer values with the filter PHP extension}

Fortunately, the filter extension comes packaged with a helpful function called “filter_var().”As its name suggests, it applies a specified filter to a given PHP variable. So, since the first step of my plan consists of demonstrating how to check if a value is an integer, I’m going to use the function to perform this task.

Now, look at the following code snippet, which makes use of a new filter named FILTER_VALIDATE_INT that checks for integers:

// example on using the FILTER_VALIDATE_INT filter

 

$input = ‘123456’;

// check to see if $input is an integer

echo filter_var($input, FILTER_VALIDATE_INT); // displays 123456

As shown above, the “filter_var()” function initially accepts two arguments. The first one is the value that will be filtered and the second one is the filter that will be applied to it. In this introductory example I wish to check if the value of the $input variable is actually an integer, so I use the FILTER_VALIDATE_INT filter.

Also, you should notice that the above example will echo the value 123456 on screen, even when the value passed in to be filtered is in reality a string. This means that the filter doesn’t care if the value is numeric or literal, as long as it contains integers.

To demonstrate this concept more clearly, here’s another example that uses the FILTER_VALIDATE_INT filter to check a true integer value:

$input = 123456;

// check to see if $input is an integer

echo filter_var($input, FILTER_VALIDATE_INT); // displays 123456

That example was pretty simple to understand, wasn’t it? Now, look at the following one, which passes a float number to the filter:

$input = 1.2;

// check to see if $input is an integer

echo filter_var($input, FILTER_VALIDATE_INT); // displays nothing

In this case, the “filter_var()” function will return FALSE and nothing will be displayed on screen, since the value passed to it is a float number. In addition, here are a couple of more readable examples that hopefully will help you grasp more quickly how the FILTER_VALIDATE_INT filter works:

$input = ‘4.56’;

if(filter_var($input, FILTER_VALIDATE_INT) === FALSE) // displays Input is not an integer.

{

echo ‘Input is not an integer.';

}

else

{

echo ‘Input is an integer.';

}

 

 

$input = ‘123456’;

if(filter_var($input, FILTER_VALIDATE_INT) === FALSE) // displays Input is an integer.

{

echo ‘Input is not an integer.';

}

else

{

echo ‘Input is an integer.';

}

As you can see in the couple of examples above, the FILTER_VALIDATE_INT filter checks if a given value is an integer or not, when used in conjunction with the “filter_var()” function. However, the filter not only permits you to validate an integer, but determine if it’s within a specified range.

This additional functionality provided by the filter will be discussed in the last segment of this tutorial. So please read the following section.

{mospagebreak title=Using the FILTER_VALIDATE_INT filter to check for minimal and maximal values}

Since you learned in the previous segment how to use the FILTER_VALIDATE_INT filter to validate integers, I’m now going to explain another way to use it. This time we’ll check not only if a given value is an integer, but if it’s within a specified range. How can this be done? It’s simple, really; adding an optional array to the “filter_var()” function allows you to specify minimal and maximal boundaries for a determined value.

The following code samples show in a nutshell how to accomplish this task in a truly intuitive way. Take a look at them:

 

$min = 1;

$max = 99;

$input = 101;

if(filter_var($input, FILTER_VALIDATE_INT, array("options" => array("min_range" => $min, "max_range"=> $max ))) === FALSE) // displays Error: Input must be a value between 1 and 99 (Correct specification for the min and max options)

{

echo ‘Error: Input must be a value between 1 and 99.';

}

else

{

echo ‘Input is correct';

}

 

$min = 1;

$max = 99;

$input = 101;

if(filter_var($input, FILTER_VALIDATE_INT, array("options" => array("max_range"=> $max ))) === FALSE) // displays Error: Input must be a value between 1 and 99 (Specifies only the max option)

{

echo ‘Error: Input must be a value between 1 and 99.';

}

else

{

echo ‘Input is correct';

}

As I said before, by adding an “options” array to the “filter_var()” function it’s possible to check not only if the inputted value is an integer, but if it belongs to a specified range. In the first case, both minimal and maximal boundaries have been specified, while in the second example, only the upper limit has been set.

From the previous code samples, it’s easy to see how useful the FILTER_VALIDATE_INT filter can be for validating integers. However, I’m only scratching the surface of the PHP 5 filter library; as you saw at the beginning, it comes packaged with many other handy filters. These will be discussed in successive articles of this series.

Final thoughts

In this initial chapter of the series, I introduced you to using the filter extension that comes included with PHP 5. As you were able to see in all of the code samples included previously, checking to see whether or not a specified value is an integer is an extremely straightforward process thanks to the help of the FILTER_VALIDATE_INT filter.

In the forthcoming article, I’m going to explain how to use the filter extension to validate array elements and to check both octal and hexadecimal integers. Don’t miss the next part!

[gp-comments width="770" linklove="off" ]

antalya escort bayan antalya escort bayan Antalya escort diyarbakir escort