views:

127

answers:

4

I have this:

foreach($_POST as $key => $value) {
    $data[$key] = filter($value);
}

filter(); strips if any tags, and real escape them.

Now I have an array in the POST form too, so I am getting errors in strip_tags() and mysql_real_escape_string. How should I let only $_POST["Searching"] not get filtered by filter(); ?

+3  A: 

You can make use of array_walk_recursive.

array_walk_recursive($_POST,'filter');

and make your function filter take the value by reference as:

function filter(&$value) {
  // apply strip_tags and real escape to $value.
  $value = mysql_real_escape(strip_tags($value));
}
codaddict
Minor syntax - shouldn't `array_walk_recursive(` be `array_walk_recursive(`? Also, just as a question for my own edification - Doesn't this function try and modify the source array in-place, rather than transcribe it to a new array, like `$data` as in the question? I see from php.net that this function only returns true or false.
Lucanos
Also call-time pass by reference is deprecated and will raise warnings. Should just be `array_walk_recursive($_POST, 'filter');`
meagar
@Lucanos,@meagar: Thanks.
codaddict
A: 

Use is_array():

foreach($_POST as $key => $value) {
    if (!is_array($value))
       $data[$key] = filter($value);
}
Parkyprg
Where in the foreach ?
Johnson
Yes, in foreach, but change $_POST['Searching'] with $value. I have changed the answer.
Parkyprg
A: 
<?php
foreach($_POST as $key => $value){
    if(!is_array($_POST[$key])){
        $data[$key] = filter($value);
    }else{
        $data[$key] = $value;
    }
}
?>
FallenRayne
This solution is incomplete - it does nothing if it hits an array. Whilst it prevents a problem with `filter()` throwing an error when it tries to handle an array, it would also mean that the array would lose data (in that any sub-arrays would be discarded).
Lucanos
You are correct. I typed my original solution too quickly.
FallenRayne
+1  A: 

First, you can use array_map() to speed this up, and all you need do is allow the function to identify arrays and call itself recursively.

function filter( $inVar ){
  if( is_array( $inVar ) )
    return array_map( 'filter' , $inVar );
  return mysql_real_escape( strip_tags( $inVar ) );
}

Then call it like so:

$data = array_map( 'filter' , $_POST );
Lucanos