Sunday, 12 May 2019

PHP/MySQL: Filtering POST & GET Data





Possible Duplicate:
What are the best PHP input sanitizing functions?






A while back I found this, what I thought to be great, snippet in someones code to filter POST and GET data from injections.



function filter($data) { //Filters data against security risks.

$data = trim(htmlentities(strip_tags($data)));
if(get_magic_quotes_gpc()) $data = stripslashes($data);
$data = mysql_real_escape_string($data);
return $data;
}
foreach($_GET as $key => $value) $filterGet[$key] = filter($value);
foreach($_POST as $key => $value) $filterPost[$key] = filter($value);


And I've been using it ever since. But today, while sending an array through ajax I got tons of errors. Most of them say strip_tags() expects parameter 1 to be string, array given in...




What the best way to filter data? All this data is going to a database. But what about cases where it isn't going to a database?


Answer



Here is the function you need:



function filter($data) { //Filters data against security risks.
if (is_array($data)) {
foreach ($data as $key => $element) {
$data[$key] = filter($element);
}

} else {
$data = trim(htmlentities(strip_tags($data)));
if(get_magic_quotes_gpc()) $data = stripslashes($data);
$data = mysql_real_escape_string($data);
}
return $data;
}

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...