开发者

PHP Santizing/Validating Array of Integers

I have the following array and would like to know what the best way would be开发者_开发技巧 of validating and santizing this array to make sure only integers are allowed?

if(is_array($_POST['taxonomy'])) {
    $term_ids = array_map('esc_attr', $_POST['taxonomy']);
}

Which looks like this when printed:

Array
(
    [0] => 13
    [1] => 12
)

I know the esc_attr isn't very secure so would like something a bit more beefed up.

Any help would be great.

Cheers,

Dave


Since it's $_POST data, you'll want to check for ctype_digit (i.e. a string containing only digits):

$sanitizedValues = array_filter($_POST['taxonomy'], 'ctype_digit');

Note that this simply discards non-numeric values.


An alternative would be using phps filter functions:

$array = array(
  13, 12, '1', 'a'
);

$result = filter_var($array, FILTER_VALIDATE_INT, array(
  'flags'   => FILTER_REQUIRE_ARRAY,
  'options' => array('min_range' => 1)
));

var_dump($result);

/*
array(4) {
  [0]=>
  int(13)
  [1]=>
  int(12)
  [2]=>
  int(1)
  [3]=>
  bool(false)
}
*/


if(is_array($_POST['taxonomy'])) {
    $term_ids = array_map('intval', $_POST['taxonomy']);
}

Should do the trick. NOTE: this is sanitation. More: http://php.net/manual/en/function.intval.php


foreach( $array as $key => $value) {
    $array[$key] = (int) $value;

    if( $array[$key] != $value ) {
        // error
    }
}


If you are looking for one-liner to check against specified condition you can use:

$onlyIntegers = Arr::check($_POST['taxonomy'], 'ctype_digit');

assuming your $_POST['taxonomy'] can contain numeric strings as @deceze suggested, or just plain:

$onlyIntegers = Arr::check($_POST['taxonomy'], 'is_int');

if you are sure that $_POST['taxonomy'] values should be in fact integers.

Arr::check method is a part of this php array library which contains various methods to help you deal with different types of arrays.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜