How to filter user submitted data easily in PHP?

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


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,


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.

25 thoughts on “How to filter user submitted data easily in PHP?

  1. 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 :)

  2. @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

  3. Christpoh

    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).


  4. @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..

  5. 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

  6. 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.

  7. @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…

  8. 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.

  9. 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 {

    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;


  10. @fluminis – Thanks for sharing this…

  11. Ian


    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.

  12. gerard

    Have you checked out Inspekt ( It wraps a “cage” around your input data and can make input filtering transparently easy.

  13. Ever heard of ?

  14. @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.

  15. 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.

  16. PHP4 is dead, php 5.1.x has critical security issues, what is the reason to do not use php 5.2.x?

  17. @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.

  18. jay

    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?

  19. Learned something new with that array_map() function. I googled it and found other great examples. Thanks for the post, just what I was looking for.

  20. I have a php site i might try this cool

  21. This is good to know, i’m always scared of people using certain characters in textfields to hack into my database, will be sure to filter everything carefully.

  22. learn something new everyday. very cool

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>