Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How to sanitize a natural number (positive INT)?

From PHP sanitize filters list there is one option to sanitize integers:

FILTER_SANITIZE_NUMBER_INT - Remove all characters except digits, plus and minus sign.

If we use:

filter_var($var2San, FILTER_SANITIZE_NUMBER_INT);

This will clean dots . and commas , but the + and - signs remain. E.g.: ++++ --- 1.110,4 <b>m<sup>2</sup></b> is sanitized to ++++---111042. Ideally the filter_var would return false when the number was 0, i.e. the number would have to be a natural number, more specifically, a positive integer.

Therefore a FILTER_SANITIZE_NUMBER_NATURAL would be handy... Is there a workaround for this or do I need a RegExp?

like image 648
Armfoot Avatar asked Jul 20 '15 15:07

Armfoot


1 Answers

Using regexp functions seems overkill, since there is another way to use the filter_var function:

filter_var($var2San, FILTER_VALIDATE_INT,
           array('options' => array('min_range' => 1)));

The FILTER_VALIDATE_INT is listed under the PHP filters flags and without defining a specific flag (in the $options array), the filter_var will detect and return the number if it is valid, returning FALSE otherwise. Examples:

  • -1FALSE
  • 0FALSE
  • 11
  • + 1FALSE
  • +22
  • ++3FALSE
  • 4+FALSE
  • 5.6FALSE
  • 7,8FALSE

This guarantees that the number you test is a natural number (a positive integer without any other characters besides digits around it, except a + at the left). Even if it has a + ahead of it, it will only return the number itself.

There is a small setback though, if the number is over 2147483647, it will also return FALSE (maximum positive value for a 32-bit signed binary integer).

like image 147
Armfoot Avatar answered Sep 27 '22 15:09

Armfoot