Forum Moderators: coopster

Message Too Old, No Replies

Checking if a filter is valid

         

csdude55

4:22 am on Oct 3, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I'm looking at these filters to use with filter_var():

[php.net...]

I've discovered that if the filter applied doesn't exist (eg, misspelled or deprecated) then filter_var() returns false instead of ignoring the bad filter. Which is the opposite of what I want, so instead I'm trying to verify that the filter is valid.

When I send, FILTER_SANITIZE_NUMBER_INT to a function as a constant and then echo it, I get a number (in this case, 257). So I need to find a way to determine whether filter_list() contains FILTER_SANITIZE_NUMBER_INT or 257.

filter_list() is a numeric array:

// print_r(filter_list());
Array
(
[0] => int
[1] => boolean
[2] => float
[3] => validate_regexp
[4] => validate_domain
[5] => validate_url
[6] => validate_email
[7] => validate_ip
[8] => validate_mac
[9] => string
[10] => stripped
[11] => encoded
[12] => special_chars
[13] => full_special_chars
[14] => unsafe_raw
[15] => email
[16] => url
[17] => number_int
[18] => number_float
[19] => magic_quotes
[20] => add_slashes
[21] => callback
)


"int" equates to "FILTER_SANITIZE_NUMBER_INT", but I can't find an automated way for the script to know that they're the same.

I can use filter_id('int'); to return 257, but I'm struggling to find a good way to go backwards; eg, I have "257" so I need to automagically equate it to "int", and then check that filter_list() contains "int".

I found this on PHP.net:

if (
$filter &&
isset(array_flip(array_map('filter_id', array_combine(filter_list(), filter_list())))[$filter]
) {
// do stuff
}

[php.net...]

It works, but it's suuuuuper slow; increasing my bench test from 0.02s to 0.46s!

Before I rely on that, is there a better / faster way to determine whether the filter given is valid?

vincevincevince

7:11 pm on Nov 2, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Your approach seems fine. My inclination on speed would be to store it in a reusable object/instance or a global variable, so you can run the isset() on it without reprocessing the array each time.