Tuesday, January 18, 2011

PHP array_map

One very useful function in PHP is array_map.

Today I am going to show you an example of how you can use this function to quickly filter possibly dangerous data in an array to prevent XSS attacks.

First you will need to create a function that will be used to clean the data:

// heres function that escapes html data to prevent xss attacks
function map_entities($str) {
    return htmlspecialchars($str, ENT_QUOTES);
} 

Next you need to apply that data to an array containing user input (in real life this could be from a $_POST or $_GET or even from a database:

// here $suspect_data is an array containing data needing to be cleaned
$safe_data = array_map('map_entities',$suspect_data);

And now our array is ready for use ... obviously there is more to filtering data then just stripping html characters, but hopefully this little tutorial is helpful in showing you how you can use array_map to solve some real life problems.

No comments:

Post a Comment