20

In reference to the filter_var function in PHP 5:

I have visited its documentation at: http://php.net/manual/en/filter.filters.sanitize.php, but I still have this question:

What are the exact differences?

For simpler clarification, please provide an example.

Cyril Graze
  • 3,881
  • 2
  • 21
  • 27
Mohammad Naji
  • 5,372
  • 10
  • 54
  • 79

2 Answers2

39

The flags are explained in a different page of the documentation.

FILTER_FLAG_STRIP_LOW strips bytes in the input that have a numerical value <32, most notably null bytes and other control characters such as the ASCII bell. This is a good idea if you intend to pass an input to another application which uses null-terminated strings. In general, characters with a Unicode codepoint lower than 32 should not occur in user input, except for the newline characters 10 and 13.

FILTER_FLAG_STRIP_HIGH strips bytes in the input that have a numerical value >127. In almost every encoding, those bytes represent non-ASCII characters such as ä, ¿, etc. Passing this flag can be a band-aid for broken string encoding, which can become a security vulnerability. However, non-ASCII characters are to be expected in virtually all user input.

To summarize:

filter_var("\0aä\x80", FILTER_SANITIZE_STRING) == "\0aä\x80"
filter_var("\0aä\x80", FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW) == "aä\x80"
filter_var("\0aä\x80", FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH) == "\0a"
filter_var("\0aä\x80", FILTER_SANITIZE_STRING,
           FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH) == "a"
phihag
  • 278,196
  • 72
  • 453
  • 469
  • 8
    It would be great if there was a STRIP_LOW_EXCEPT_NEWLINB flag, since there is a use case for keeping newline characters from textarea-fields. Alas, there is none, so that special case must be handled. – itpastorn Jul 14 '13 at 22:33
  • something is not working in your examples, please have a look https://eval.in/935865 – Yevgeniy Afanasyev Jan 17 '18 at 01:09
  • 1
    @YevgeniyAfanasyev Thank you for the note. I have fixed the answer. Escapes in string literals only work in double quotes in php. – phihag Jan 17 '18 at 01:53
3
FILTER_FLAG_STRIP_LOW

Remove characters with ASCII value < 32

FILTER_FLAG_STRIP_HIGH

Remove characters with ASCII value > 127

Peyman Mohamadpour
  • 17,954
  • 24
  • 89
  • 100
ian
  • 77
  • 3