0

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(); ?

4 Answers 4

3

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));
}
Sign up to request clarification or add additional context in comments.

2 Comments

Minor syntax - shouldn't array_walk_recursive(&$_POST,filter); be array_walk_recursive(&$_POST,'filter');? 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.
Also call-time pass by reference is deprecated and will raise warnings. Should just be array_walk_recursive($_POST, 'filter');
1

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

Comments

0

Use is_array():

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

1 Comment

Yes, in foreach, but change $_POST['Searching'] with $value. I have changed the answer.
0
<?php
foreach($_POST as $key => $value){
    if(!is_array($_POST[$key])){
        $data[$key] = filter($value);
    }else{
        $data[$key] = $value;
    }
}
?>

1 Comment

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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.