Clearing form data in PHP

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

$var = mysql_real_escape_string($_POST);

      

and then access the $ var items that I would use in $ _POST?

+1


a source to share


5 answers


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

But it will work

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

      



array_map works by calling the quoted function for each element of the array passed to it and returning a new array as the result.

As superUntitled , I prefer to have a custom function that uses the built-in sanitization functionality as needed. But you can use a custom function with array_map to achieve the same result.

+9


a source


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

      

+1


a source


this function will remove html tags from everything you pass to it

function strip_html(&$a){
    if(is_array($a)){
        foreach($a as $k=>$v){
            $a[$k]=preg_replace('/<[^<]+?>/','',$v);
        }
    }else{
            $a=preg_replace('/<[^<]+?>/','',$a);
    }
    return;
}

      

+1


a source


What I'm comfortable with is to encapsulate the request data (Post, Get, Cookie, etc.) in Object and then add a filter method that can pass an array of function names. So you can use it like this:

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

      

The body of the method works using an array_map loop, as in Mark's example. I would not run mysql_real_escape_string all over my $ _POST though, only on the required fields (the ones requested or inserted)

0


a source


@Shadow:

Array_Map will work with one-dimensional arrays, but it won't work with multi-dimensional arrays. So this will work.

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

but if this $ _POST array should have another array like: $array = $_POST['myArray']['secondArray'];

If you have an array like the one shown above, the array map will throw an error when you try to run a function that only takes a String as an argument, because it will not process the array when it only expects a string.

The solution presented on the next page is much more convenient and recursive for each element within the array.

PHP -Sanitize array values

0


a source







All Articles