How to filter user submitted data easily in PHP?
- Tuesday, August 12, 2008, 18:45
- php, tips and technique
- 20 comments
Yesterday, I saw one of my friend was working on the the contact form and was filtering the user input data(posted variables) individually. He was using a function in PHP to filter the input and using tedious approach while calling the filtering function for each variables with coding each of them in single line . Today, I’m going to show you how can you filter the posted variables easily using callback function in PHP.
PHP function to filter the user supplied data.
function filter_data($val)
{
return htmlentities($val,ENT_QUOTES);
}
This is just a example of very simple function is PHP to filter the user ssubmitted data.But ,you can add more code according to your requirement to make this function robust.
Common programmer’s approach to filter submitted data in PHP
$name=filter_data($_POST['name']); $email=filter_data($_POST['email']); $website=filter_data($_POST['website']);
It was the approach which I’ve used in beginning of my career and most of the beginner PHP programmer use this approach to filter the posted variables.And, the above list can be long if there are more posted data.At that time, it will be very irritating to use the same kind of line in many places.
Using array_map() function to filter the posted data in PHP
As you know, POST variables are super global array in PHP and you can use array_map() function in PHP to filter the input using the callback function. Let’s see how you can filter the the posted data easily,
$post=array_map("filter_data",$_POST);
As you can, each values of POST variables is mapped into another array using a call back function filter_data() which is defined above.
Now, you can access the filtered variables easilly with $post['name'] or $post['email'] etc.
Popularity: 11%
Related Posts
» Cross-site scripting ( xss ) attack by example and prevention in PHP
» Creating and Parsing JSON data with PHP
» A ajax tutorial for beginners
» Uploading large(big) files in PHP using .htaccess
20 Comments on “How to filter user submitted data easily in PHP?”
Trackbacks
- How to filter user submitted data easily in PHP? | coderchris.com
- [??] Aug 23th 2008 « Oceanic | ????






i didn’t know you can do that i must admit. nice and enlightening post!
PS: you must add a small javascript that won’t let me submit unless i fill the spam protection.. i keep forgetting the damn thing
@stratosg - There is one rule in web development “Never ever trust the user supplied data”.
A hacker is a human and can easily enter the spam protection value then supply malicious code in user supplied data for XSS or SQL Injection attack etc..
So, you must filter the user supplied data though you’ve spam protection in your web form
Nice post, again!
Complete this with a final extract ($post) and you can access $name, $email, $website, (according to the names you´ve given the form fields).
Cheers!
@christpoh - yes you can use extract($post) to extract array key into variable but beware that extract() to use with optional parameter othewise it may replace the existing variables..
what i said is not on the post about filtering… what i said is that you should keep the spam protection but add a small javascript to remind me to fill it cause i submit the form and forget about it and i get the error and loose my message… i agree on what you said though…
ps: sry for the offtopic
Don’t forget submitted forms don’t just hold strings, they can also hold arrays.
Your approach is right for the mass-escaping, but you have to make it recursive so that you only escape leaf nodes of the original form.
Also, do NOT html-escape form contents before you process it (ie, check for its validity), but just before you html-render it.
@Gromitt - yes for html for containing array you’ve to slighly modify this approach and regarding validation you can create a array for error message and validate inside filter_data() function before html rendering it…
It’s a good basic approach, however it’ll cause you more grief than pleasure when you need specific filtering rules for certain fields.
A detailed ereg() for e-mail validation, another one for VAT-numbers, ZIP postal codes, serial numbers, …
As said before, it’s a good way to addslashes(), htmlspecialchars() or nl2br() a lot fields at the same time - but it will still require a lot of work if you want proper, field-based, validation - without a lot of overhead.
Interesting article.
I use to have a single function to validate user data :
if (verifyFields($_POST, array(
‘field1′ => array(’required’, ‘number’, ‘positive’),
‘field2′ => array(’string’)))) {
//everything ok
} else {
//error
}
And the function looks like :
function verifyFields($myArray, $fields) {
foreach($fields as $field => $checks) {
foreach($checks as $check) {
if ($check == ‘required’ && !isset($myArray[$field])) {
return false;
}
if(isset($myArray[$field])) {
if ($check == ‘number’ && !ctype_digit($myArray[$field])) {
return false;
}
…
}
}
}
}
@fluminis - Thanks for sharing this…
@Roshan
Noooo! Don’t encourage people to use extract() on $_POST or any other user input superglobal for that matter! That’s precisely the problem with register_globals.
If you extract() all of the variables in an input array, you open up the very real possibility that an internal variable that you didn’t intend for users to interact with can now be initialized with anything the user wants.
They could for example, post a variable called content and fill it with javascript. If you happen to use a variable $called content in your code and don’t initialize it with an empty string before concatenating to it, that javascript may be passed back out to the page when you echo $content.
Have you checked out Inspekt (http://inspekt.org)? It wraps a “cage” around your input data and can make input filtering transparently easy.
Ever heard of http://www.php.net/filter ?
@gerard - Thanks for the link of inspekt it seems to be a nice tool..will check it later in free time
@Pierre - Thanks but you must have PHP greater than 5.2.0 and not useful for people who are using lower version of PHP.
I couldn’t echo Mojah’s comment more strongly. The best practice when it comes to user input is to validate input (make sure it is the type/size you expect) and filter/encode/etc. output. You do the later ONLY when it is being output because you never know what the data will be used for between when it is input and when the script ends.
As for the filter extension, I recommend this as well. It is available as a pecl extension for those of you still stuck on PHP 5 < 5.2 (if you are using PHP 4.x, WHY?!). You can use it to force a base level of security on all inputs and to get any user data you need to use the filter_input function.
PHP4 is dead, php 5.1.x has critical security issues, what is the reason to do not use php 5.2.x?
@john - Thanks for your explanation
@Pierre - I can see still in some of of the web hosting company are using PHP4 and PHP 5.1.x , I’m just worried for them only otherwise I’m not against PHP’s filter extension, I also recomment this if you’re using PHP 5>5.2.0.
In your example you have written a general function so that when a variable is required to be validated. you just call that function.
function filter_data($val)
{
return htmlentities($val,ENT_QUOTES);
}
What if you want to replace that htmlentities with filter_input ( ) can the input type parameter for this be POST?