Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP 5.4: Can I use multiple flags with a filter using filter_var_array()?

Tags:

php

PHP Manual: filter_var_array()

mixed filter_var_array ( array $data [, mixed $definition [, bool $add_empty = true ]] )

Can something like this for the $definition argument of a filter_var_array() call ever work? (array syntax >= PHP5.4)

   $def = [
         'firstName' => ['filter' => FILTER_SANITIZE_STRING,
                         'flags'  => [FILTER_REQUIRE_SCALAR | FILTER_FLAG_NO_ENCODE_QUOTES | FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH]],
         'lastName'  => ['filter' => FILTER_SANITIZE_STRING,
                         'flags'  => [FILTER_REQUIRE_SCALAR | FILTER_FLAG_NO_ENCODE_QUOTES | FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH]],
   ];

Is using only one flag at a time the only way to use flags when using filter_input_array()? For example: (written out the long way, although I could do this with a loop).

   $def1 = [
         'firstName' => ['filter' => FILTER_SANITIZE_STRING,
                         'flags'  => FILTER_REQUIRE_SCALAR],
         'lastName'  => ['filter' => FILTER_SANITIZE_STRING,
                         'flags'  => FILTER_REQUIRE_SCALAR]
   ];

   $def2 = [
         'firstName' => ['filter' => FILTER_SANITIZE_STRING,
                         'flags'  => FILTER_FLAG_NO_ENCODE_QUOTES],
         'lastName'  => ['filter' => FILTER_SANITIZE_STRING,
                         'flags'  => FILTER_FLAG_NO_ENCODE_QUOTES]
   ];

   $def3 = [
         'firstName' => ['filter' => FILTER_SANITIZE_STRING,
                         'flags'  => FILTER_FLAG_STRIP_LOW],
         'lastName'  => ['filter' => FILTER_SANITIZE_STRING,
                         'flags'  => FILTER_FLAG_STRIP_LOW]
   ];

   $def4 = [
         'firstName' => ['filter' => FILTER_SANITIZE_STRING,
                         'flags'  => FILTER_FLAG_STRIP_HIGH],
         'lastName'  => ['filter' => FILTER_SANITIZE_STRING,
                         'flags'  => FILTER_FLAG_STRIP_HIGH]
   ];
like image 819
Anthony Rutledge Avatar asked May 11 '15 15:05

Anthony Rutledge


1 Answers

Just make sure you do not put the flags inside their own array. Options can be in an array, but the flags need to be seen as one whole thing separated by the bitwise OR operator (|).

   $def = [
      'firstName' => ['filter' => FILTER_SANITIZE_STRING,
                       'flags' => FILTER_REQUIRE_SCALAR | FILTER_FLAG_NO_ENCODE_QUOTES | FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH],
      'lastName'  => ['filter' => FILTER_SANITIZE_STRING,
                       'flags' => FILTER_REQUIRE_SCALAR | FILTER_FLAG_NO_ENCODE_QUOTES | FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH]
   ];
like image 66
Anthony Rutledge Avatar answered Nov 07 '22 01:11

Anthony Rutledge