Cleaning up Array Elements, POST and GET Requests with Filters in PHP 5

Welcome to the final episode of a series that shows you how to use filters in PHP 5. Made up of nine parts, these articles show you how to utilize the numerous checking filters that come with the filter library. You can use them to thoroughly validate the incoming data handled by your PHP programs, without having to spend a long time coding custom functions or class methods.

Naturally, if you’ve been a patient reader and already went through the preceding articles of the series, I’m certain that at this point you’ll have a solid background in using the filter extension for checking common data types, including email and IP addresses, integers and float numbers, and so forth. In those tutorials I explained how to accomplish all of these tasks with a decent variety of code samples.

Regardless of the features mentioned before, one of the most robust aspects of the filter library is its ability to sanitize strings, something that was covered in depth in the previous chapter. However, the library is also capable of cleaning up strings in arrays, as well in data coming from GET and POST requests and cookies. Therefore, this final article of the series will demonstrate how to do this with a few understandable examples, in this manner concluding this quick introduction to working with the PHP 5 filter library.

So, are you ready to tackle the last episode of this educational journey? Then don’t waste more time; start reading now!

{mospagebreak title=Review: the FILTER_SANITIZE_STRING filter}

Just in case you haven’t read the previous article of this series, where I demonstrated how to use the filter extension for sanitizing different types of strings, below I reintroduced the code samples developed in that article. This way, you can quickly learn how to perform this task with minor hassles.

That being said, here’s how the aforementioned examples were created originally:

 

// example on sanitizing strings in a basic way

$string = ‘<script>alert(‘hello’);</script>';

echo filter_var($string, FILTER_SANITIZE_STRING); // quotes are encoded

 

 

// example on sanitizing strings using the FILTER_FLAG_NO_ENCODE_QUOTES argument

$string = ‘<script>alert(‘hello’);</script>';

echo filter_var($string, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES); // quotes are not encoded

 

 

// example on sanitizing strings using the FILTER_FLAG_STRIP_LOW argument

$string = ‘<script>#$%^&!*</script>';

echo filter_var($string, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW); // strips low characters

 

 

// example on sanitizing strings using the FILTER_FLAG_STRIP_HIGH argument

$string = ‘<script>This is a string#$%^&!*</script>';

echo filter_var($string, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH); // strips high characters

 

 

// example on sanitizing strings using the FILTER_FLAG_ENCODE_LOW argument

$string = ‘<script>This is a string#$%^&!*</script>';

echo filter_var($string, FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW); // encodes low characters

 

 

// example on sanitizing strings using the FILTER_FLAG_ENCODE_HIGH argument

$string = ‘<script>This is a string#$%^&!*</script>';

echo filter_var($string, FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_HIGH); // encodes high characters

 

// example sanitizing an email address using the FILTER_SANITIZE_EMAIL filter

$email = ‘alejandro(&)gervasio@domain.com';

echo filter_var($email, FILTER_SANITIZE_EMAIL); // sanitizes email address

 

 

// example sanitizing a URL using the FILTER_SANITIZE_URL filter

$email = ‘http://www.devshed.c!m';

echo filter_var($email, FILTER_SANITIZE_URL); // removes invalid characters from a URL

 

 

// example sanitizing an integer using the FILTER_SANITIZE_NUMBER_INT filter

$value = ’12abc345@';

echo filter_var($value, FILTER_SANITIZE_NUMBER_INT); // sanitizes an integer

 

 

// example sanitizing a float number using the FILTER_SANITIZE_NUMBER_FLOAT filter

$value = ’12.abc345@';

echo filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT); // sanitizes a float number and converts it to an integer

 

 

// example sanitizing a float number using the FILTER_SANITIZE_NUMBER_FLOAT filter and the FILTER_FLAG_ALLOW_FRACTION argument

$value = ’12.abc345@';

echo filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION); // sanitizes a float number

 

 

// example sanitizing a float number using the FILTER_SANITIZE_NUMBER_FLOAT filter and the FILTER_FLAG_ALLOW_THOUSAND

$value = ’12.,abc345@';

echo filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_THOUSAND); // sanitizes a float number

 

 

// example sanitizing magic quotes using the FILTER_SANITIZE_MAGIC_QUOTES filter

$value = "I’m Alejandro Gervasio";

echo filter_var($value, FILTER_SANITIZE_MAGIC_QUOTES);

As you no doubt realized when examining the above sample codes, it’s extremely simple to sanitize distinct kinds of data by using the FILTER_SANITIZE_STRING filter in conjunction with several constants, which are passed to the familiar “filter_var()” function. In doing so, it’s possible to remove unwanted characters from email addresses and numeric values, as well as encode quotes, only to cite some illustrative examples that can be recreated in real world environments.

Now that you hopefully recalled the basic concepts that surround the implementation of the FILTER_SANITIZE_STRING filter for sanitizing strings in all sorts of clever ways, it’s time to explore a few more features provided by the filter extension, which also can be helpful for cleaning up literals.

With this idea in mind, in the course of the following section I’m going to explain how to use the FILTER_SANITIZE_STRING filter for cleaning up data coming from GET and POST HTTP requests and from cookies as well.

If you wish to learn the full details of this topic, click on the link that appears below and read the upcoming segment.

{mospagebreak title=Sanitizing strings from GET and Post requests, cookies and sessions}

As I expressed in the section that you just read, the filter library also has the ability to directly sanitize data that comes from GET and POST requests and from cookies and sessions as well. These options can be pretty useful alternatives to the validation filters covered in previous articles of the series. They can be implemented with a brand new function called “filter_input().”

To demonstrate how this function can be utilized, below I created some basic examples that show how to filter variables coming from GET and POST requests, and from sessions and cookies as well. Here they are:

// example on using the INPUT_GET filter

echo filter_input(INPUT_GET, "age", FILTER_SANITIZE_NUMBER_INT);

 

// example on using the INPUT_POST filter

echo filter_input(INPUT_POST, "age", FILTER_SANITIZE_NUMBER_INT);

 

// example on using the INPUT_REQUEST filter

echo filter_input(INPUT_REQUEST, "age", FILTER_SANITIZE_NUMBER_INT);

 

// example on using the INPUT_COOKIE filter

echo filter_input(INPUT_COOKIE, "age", FILTER_SANITIZE_NUMBER_INT);

 

// example on using the INPUT_SESSION filter

echo filter_input(INPUT_SESSION, "age", FILTER_SANITIZE_NUMBER_INT);

Definitely, you should be able to quickly grasp how the “filter_input()” function does its business, since its usage is extremely intuitive. In the first three examples shown above, the function has been used for filtering a fictional “age” variable inputted via a GET and POST web form (or an eventual hyperlink, too), while the remaining code samples illustrate how to sanitize data stored in a session variable and a cookie. Simple to code and read, isn’t it?

Well, at this stage I’m sure that you’re familiar with using the “filter_input()” function for validating GET, POST and COOKIE data in a truly painless fashion. Therefore, the last topics that I’m going to discuss in this article will be focused on showing how to utilize the filter library with callback functions, and how to create an array of filters.

As usual, to see how these tasks will be accomplished, please read the following section. We’re almost finished.

{mospagebreak title=Using callback functions and building arrays of filters}

Any introduction to working with the PHP 5 filter extension wouldn’t be complete if it didn’t mention the capabilities for using filters in conjunction with callback functions and for building arrays of filters. Yes, the filter library permits you to do this in a simple manner, as you’ll see from the couple of examples listed below. Pay close attention to them:

// example on using the FILTER_CALLBACK filter with user defined function

function nl2par($str)

{

return str_replace("n",'<p>’, $str);

}

$string = "This is a linenThis is another line";

echo filter_var($string, FILTER_CALLBACK, array(‘options’ => ‘nl2par’));

 

 

// example on using the FILTER_CALLBACK filter with PHP function

$string = "This is a linenThis is another line";

echo filter_var($string, FILTER_CALLBACK, array(‘options’ => ‘nl2br’));

 

 

// example on using an array of filters

$_POST = array(‘name’ => ‘Alejandro Gervasio’, ‘email’ => ‘alejandro@domain.com’);

// build an array of filters

$filters = array(‘name’ => FILTER_SANITIZE_STRING, ‘email’ => FILTER_VALIDATE_EMAIL);

// run filters

$filteredValues = filter_var_array($_POST, $filters);

// display filtered values

foreach($filteredValues as $key => $value)

{

echo $key . ‘ — ‘ . $value .'<br />';

}

As you can see above, it’s perfectly feasible to bind different callback functions to a specific filter using the “filter_var()” function. In the first example, this process is performed by using a custom function called “nl2par(),” while in the second case this same task is carried out by means of a native PHP function like “nl2br().”

Finally, there’s an additional code sample that shows how to build an array of filters, which can be applied later on to elements of another input array, such as the superglobal $_POST, $_GET, etc.

And with these examples, I’m concluding this introductory overview on using the filter extension that comes bundled with PHP 5. Of course, you’re completely free to edit and enhance all of the code samples developed in this article series, thus arming yourself with a strong background in working with this powerful validation library.

Final thoughts

Sad but true, we’ve come to the end of this series. Hopefully this long journey has been instructive for you, since you learned how to take advantage of the impressive functionality provided by the PHP 5 filter library. So, now that you’re aware of its existence, the next time that you need to validate incoming data within your PHP applications, you should consider using this extension as a good alternative to coding custom checking functions.

See you in the next PHP tutorial!

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

chat