PHP - How to check if an input filter is valid?

395 Views Asked by At

I've got a function that takes a filter constant for filter_input as an optional parameter. Is it possible to make sure the value of the string is a valid PHP filter constant, perhaps with a built in PHP function?

I know one way is to make my own array of all filter constants and check against that, but I was hoping for an easier or better way.

2

There are 2 best solutions below

2
hakre On BEST ANSWER

You could verify against the list of filters:

$valid = in_array($filter, filter_list(), true);

Where $filter contains the user supplied filter value and $valid the result as a bool (true if valid, false if invalid).

See filter_list() in the PHP manual for more details.

3
Bruno Leveque On

I was able to achieve this by using the get_defined_constants() PHP built-in function, which list all predefined PHP constants.

Solution:

The code below will store all the allowed filters into an array and allow you to check any filter's validity via the check_filter() function.

<?php

$constants = get_defined_constants();
$allowed_filters = array();
foreach ($constants as $c => $val)
    if (substr($c, 0, 7) == 'FILTER_')
        $allowed_filters[$c] = 1;

function check_filter($filter_name, $allowed_filters) { return isset($allowed_filters[$filter_name]); }

var_dump(check_filter('FILTER_SANITIZE_EMAIL', $allowed_filters)); // true
var_dump(check_filter('FILTER_TEST', $allowed_filters)); // false
var_dump(check_filter('PHP_VERSION', $allowed_filters)); // false, even though constant exists

I hope this helps!