PHP can (should) I array_map filter_var to $_POST

2019-08-24 10:13发布

问题:

I just stumbled on this neat bit of code to filter $_POST data quickly:

$post=array_map("filter_data",$_POST);

I've updated it to the new version (after PHP 5.2) and I've got

$post=array_map("filter_var",$_POST,array(516));  // 516 == 'unsafe_raw'

Now I'm paranoid; this seems too easy. So

  • Should I not do this for all post data? (shifty nervous eyes)
  • Is unsafe_raw the correct filter for generic post, get, or cookie data?

I should add I'm just trying for a general sanitizer, mainly to remove SQL injections. If I have an email address or something I can filter again later. Any ideas / suggestions / horrified stares?

回答1:

To avoid SQL injection, always use the appropriate functions for your database just before plugging the value into the query string, e.g. mysql_real_escape_string. A general filter not specific to your database doesn't guarantee anything and will probably only filter too much.

For anything else, like email validation, use the specific filter on the specific variable that holds the email address.

Also, use the constant FILTER_UNSAFE_RAW, not its numeric value.