PHP: foreach and array issue
I h开发者_StackOverflow中文版ave 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();
?
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));
}
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 );
Use is_array():
foreach($_POST as $key => $value) {
if (!is_array($value))
$data[$key] = filter($value);
}
<?php
foreach($_POST as $key => $value){
if(!is_array($_POST[$key])){
$data[$key] = filter($value);
}else{
$data[$key] = $value;
}
}
?>
精彩评论