PHP escaping input variables
I'm using followi开发者_如何学Cng function to protect my db from injection attacks and etc. for gets
.
function filter($data) {
global $db;
$data = trim(htmlentities(strip_tags($data)));
if (get_magic_quotes_gpc())
$data = stripslashes($data);
$data = $db->real_escape_string($data);
return $data;
}
foreach($_GET as $key => $value) {
$data[$key] = filter($value);
}
Question is, i want to filter not only $_GET
but $_POST
too. How to do that?
And can I reassign value to $_GET
or $_POST
after filtering? I mean $_GET[$key] = filter($value);
instead of $data[$key] = filter($value);
..
Don't pre-escape your variables, escape them only at the time you need to escape them.
- If you prematurely escape your variable, you'll never know which variable is escaped, and which is not
- You'll have to unescape your variables before doing string manipulations, and re-escape them after
- Variables coming from different sources (like from an API, from a file or even from your database) won't be escaped. You'll forget to escape them.
- You'll have to un-escape all your variables before printing them (you don't want to print the \', I guess)
- You can't escape a variable for every possible situation. What about escaping them with escapeshellcmd too ?
PHP did this in the past. It was called magic_quotes_gpc
.
But it's so bad practice that it's now deprecated, and it will be removed from the next version of PHP.
It's better to just escape everything at the time you need to. You print a variable ? escape it. You don't have to remember if it's already escaped or not: it's not.
this function makes no sense.
and it doesn't filter anything.
and shouldn't be used this way.
to protect your db from injection attacks you shouldn't do most of the things present in this function and should do many things not present there.
to protect only strings (data chunks enclosed in quotes) from injection attacks you have to use $db->real_escape_string and nothing else.
to protect other query parts you have to use other procedures, as real_escape_string become utterly useless for them
to protect your app from "etc attacks" you have to define what is this "etc" first.
array_walk($_GET,'filter');
array_walk($_POST,'filter');
array_walk($_COOKIE,'filter');
You should probably filter the $key too in case you use it in the query later, but if possible you should use mysql prepared statements and bind variables.
http://www.ultramegatech.com/blog/2009/07/using-mysql-prepared-statements-in-php/
You can change $_GET and $_POST.
精彩评论