tags:

views:

477

answers:

3

Is it possible to sanitize all input sent by one method in PHP by simply doing

$var = mysql_real_escape_string($_POST);

and then access elements of $var as I would have of $_POST ?

+4  A: 

I don't think you can call mysql_real_escape_string on an array.

But this would work

$cleanData = array_map('mysql_real_escape_string', $_POST);

array_map works by calling the function named in quotes on every element of the array passed to it and returns a new array as the result.

Like superUntitled, I prefer to have a custom function that uses the built-in sanitizing functions as appropriate. But you could still use a custom function with array_map to achieve the same result.

Mark Biek
Thanks Mark, I did not know about the array_map function, props!
superUntitled
It's a handy one :)
Mark Biek
Could one include in their "escape" function a check-for-array statement, and if it is an array, sanitize all of the elements in the array with the array_map function
superUntitled
Certainly could. Just use is_array() (and is_object(), if you wanted to catch that too).
ceejayoz
I'm not sure that would work if your escape function had multiple paths for sanitizing a value, like your example below.
Mark Biek
A: 

As a side note, I would recommend using a function to sanitize your results:

function escape($txt) {
    if (get_magic_quotes_gpc())
        $txt = stripslashes($txt);

    if (!is_numeric($txt))
        $txt = "'" . mysql_real_escape_string($txt) . "'";

   return $txt;
}
superUntitled
A: 

What I find handy is to encapsulate the request data (Post, Get, Cookie etc) in to an Object and then to add a filter method which u can pass an array of function names to. This way you can use it like this:

$array = array('trim','mysql_real_escape_string');
$request->filter($array);

Body of the method works using a loop an array_map like in Mark's example. I wouldn't run the mysql_real_escape_string over my entire $_POST though, only on the necessary fields ( the ones that are getting queried or inserted )

xenon