How to filter user submitted data easily in PHP?

Advertisement

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.

Enter your email address and get free tutorials, tips and tricks of PHP, Ajax, JavaScript and CSS directly delivered to you email inbox:

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

  • stratosg wrote on 12 August, 2008, 22:44

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

  • Roshan wrote on 13 August, 2008, 4:30

    @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

  • Christpoh wrote on 13 August, 2008, 4:32

    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!

  • Roshan wrote on 13 August, 2008, 6:43

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

  • stratosg wrote on 13 August, 2008, 11:08

    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

  • Gromitt wrote on 13 August, 2008, 18:02

    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.

  • Roshan wrote on 14 August, 2008, 4:53

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

  • Mojah wrote on 14 August, 2008, 6:16

    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.

  • fluminis wrote on 14 August, 2008, 14:01

    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;
    }

    }
    }
    }
    }

  • Roshan wrote on 14 August, 2008, 16:14

    @fluminis – Thanks for sharing this…

  • Ian wrote on 14 August, 2008, 18:01

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

  • gerard wrote on 15 August, 2008, 15:40

    Have you checked out Inspekt (http://inspekt.org)? It wraps a “cage” around your input data and can make input filtering transparently easy.

  • Pierre wrote on 15 August, 2008, 15:43

    Ever heard of http://www.php.net/filter ?

  • Roshan wrote on 15 August, 2008, 16:50

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

  • John J. wrote on 15 August, 2008, 21:05

    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.

  • Pierre wrote on 16 August, 2008, 21:59

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

  • Roshan wrote on 17 August, 2008, 5:16

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

  • jay wrote on 2 December, 2008, 5:15

    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?

  • beats wrote on 7 February, 2009, 3:10

    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.

  • mello wrote on 10 October, 2009, 16:15

    I have a php site http://www.phloentertainment.com i might try this cool

  • sell music beats wrote on 16 December, 2009, 0:35

    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.

  • Jacob Poore wrote on 28 February, 2010, 17:15

    learn something new everyday. very cool

Trackbacks

  1. How to filter user submitted data easily in PHP? | coderchris.com
  2. [??] Aug 23th 2008 « Oceanic | ????
  3. [??] Aug 23th 2008 - My Habari

Write a Comment

 


Copyright © 2014 Roshan Bhattarai's Blog. All rights reserved.
Powered by WordPress.org, Custom Theme and ComFi.com Calling Card Company.