Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question

4 Answers 4

up vote 0 down vote accepted

Use is_array():

foreach($_POST as $key => $value) {
    if (!is_array($value))
       $data[$key] = filter($value);
}
share|improve this answer
    
Where in the foreach ? –  Johnson Oct 6 '10 at 15:48
    
Yes, in foreach, but change $_POST['Searching'] with $value. I have changed the answer. –  Parkyprg Oct 6 '10 at 15:49

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));
}
share|improve this answer
    
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. –  Lucanos Oct 6 '10 at 15:53
    
Also call-time pass by reference is deprecated and will raise warnings. Should just be array_walk_recursive($_POST, 'filter'); –  meagar Oct 6 '10 at 15:59
    
@Lucanos,@meagar: Thanks. –  codaddict Oct 6 '10 at 16:09

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 );
share|improve this answer
<?php
foreach($_POST as $key => $value){
    if(!is_array($_POST[$key])){
        $data[$key] = filter($value);
    }else{
        $data[$key] = $value;
    }
}
?>
share|improve this answer
    
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 Oct 6 '10 at 15:51
    
You are correct. I typed my original solution too quickly. –  FallenRayne Oct 6 '10 at 16:02

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.