Home > PHP, Web Development > How to filter user submitted data easily in PHP?

How to filter user submitted data easily in PHP?

How to filter user submitted data easily in PHP?

Posted using ShareThis

Firstly, as you can see this is my first post made as a direct result of using the ShareThis bookmarklet, which is pretty neat as it actually worked :)

Secondly and more importantly, I wanted to flag this up on my blog as it's something that quite often gets missed in PHP which is actually a very powerful tool.

As the author of the post above mentions, array_map() can be a useful function when sanitizing user data, but it has so many more uses too when dealing with the transformation of a data-set.

Basically a call such as $new_data = array_map('process_data', $old_data); will allow you to transform each element in the $old_data array to a new element in the $new_data array via the function called process_data.

What's more you can manipulate multiple data-sets in this way too by specifying multiple arrays, so long as process_data() can take in the arguments.

For example lets say we have process_data($item1, $item2, $item3) which manipulates $item1, $item2, $item3 to produce a single result.

If we need to perform this calculation on a bulk set of data we can do

$new_data = array_map('process_data', $array_of_item1, $array_of_item2, $array_of_item3);

Easy huh?

I still see people performing these transformations, calculations, whatever, using for, foreach and while loops which can be prone to failure under certain conditions, and are probably less efficient code than simply making this call.

So why don't more people use it?  I don't know, but maybe this post will help raise awareness!

Related posts on coderchris.com:

  1. User Agent
    Of all the websites out there that I visit on a daily basis, I wonder...
  2. Advanced Syntax-Hilighting Online Code Editors – A Wordpress IDE?
    When I write plugins for wordpress I like to do it on a test blog...
  3. Handling CType Data With SimpleXML in PHP
    If you're new to SimpleXML then the output and representation of complex XML data produced...
  4. Wordpress 2.5 Released!
    Version 2.5 of wordpress has been released and we have a nice new admin interface at...
  5. Simple Function To Force Download Of A File
    The following function will allow you to run a file download through PHP, you could...

  1. November 27th, 2008 at 09:52 | #1

    I personally don’t use array map because it’s all well and good when you’re expecting only strings to come through for filtering, but if you’re expecting integers to make up dates and the like, using array map in my experience has always resulted in going back and fixing stuff, or having to do more filtering anyway so it’s a bit of a waste of time.

    Maybe I just haven’t thought about it enough.

  1. No trackbacks yet.