Php - filter_input - set the default value if the GET key is not set

I would like to have a clean and elegant way to set a variable to a GET parameter if the specified parameter is set (and numeric) and 0 (or some other default) if it is not set.

Now I have:

if (($get_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT))) { $opened_staff['id'] = $get_id; // some database queries etc. } else { $opened_staff['id'] = 0; } 

I tried using a callback function that returns 0 if the value is null or not numeric, but if the GET ID parameter is not set, the callback will not even be called - it just sets $get_id to zero.

You should not include the else expression, I just thought that I could miss some filter_input functions.

+6
source share
2 answers

The filter_input function accepts the options parameter. Each filter accepts different parameters. For example, the FILTER_VALIDATE_INT filter can accept default , min_range and max_range parameters as described here .

 $get_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT, array("options" => array( "default" => 0, "min_range" => 0 ))); var_dump($get_id); // $get_id = 0 when id is not present in query string, not an integer or negative // $get_id = <that integer> otherwise 
+14
source

You can use the default option to achieve this. If the value is not set, the default value will be assigned, for example, as follows

 $options = array( 'options' => array('default'=> 0) ); $valid = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT, $options); 

filter_input () cannot be read from _POST / _GET / _COOKIE / _SERVER / _ENV

 $opened_staff['id'] = 0; if($valid){ $opened_staff['id'] = $_GET['id']; } 

You can use some class to achieve this. [NOTE: - this is just an example]

 class RequestFilter{ public static function get_filter_int($id){ $options = array( 'options' => array('default'=> 0) ); $valid = filter_input(INPUT_GET, $id, FILTER_VALIDATE_INT, $options); if($valid){ return $_GET[$id]; // Value will return } return $valid; // Default will return } } $opened_staff['id'] = RequestFilter::get_filter_int('id'); 

here it will return the value or the default value, here it is zero.

+3
source

Source: https://habr.com/ru/post/978499/


All Articles