kujiy
kujiy

Reputation: 6137

PHP filter_input(): doesn't apply default value when $_GET["var"] is set but empty

PHP filter_input() doesn't return its default value when the input is exist but empty

Let me assume that we have a page with this php code.

<?php

$keyword = filter_input(INPUT_GET, 'keyword', FILTER_DEFAULT, array("options" => array(
    "default" => "default_value"
)));

echo $keyword;  
  1. When I open this page with this URL which has keyword param and a value;

http://example.com/?keyword=abc

It will return

abc
  1. When I open the page with this URL which has only keyword param;

http://example.com/?keyword=

It will return

// nothing returned

I hoped default_value will be returned.

Do you know something about that?

Upvotes: 1

Views: 1057

Answers (2)

Funk Forty Niner
Funk Forty Niner

Reputation: 74217

What's happening here is that only keyword is used as a filter, therefore it's not going to show you anything else.

Had keyword= been in its place, it would have shown you the default value.

Therefore, you're probably best to use a ternary operator and check if the GET array is empty.

A partial solution to this, and using your present code would be and using a conditional !empty() (NOT EMPTY):

<?php

$keyword = filter_input(INPUT_GET, 'keyword', FILTER_DEFAULT, array("options" => array(
    "default" => "default_value"
)));

if(!empty($keyword)){

   echo $keyword;

}

else{

   echo "The array is empty.";

}

or as a ternary operator:

<?php

$keyword = filter_input(INPUT_GET, 'keyword', FILTER_DEFAULT, array("options" => array(
    "default" => "default_value"
)));

echo $keyword = $keyword ? $keyword : "default_value";

Sidenote: echo $keyword = ... is valid syntax. It both echo's and assigns at the same time.

Upvotes: 0

cFreed
cFreed

Reputation: 4484

With FILTER_DEFAULT filter, no option is available (see FILTER_UNSAFE_RAW at http://php.net/manual/en/filter.filters.sanitize.php).

Otherwise FILTER_DEFAULT doesn't filter anything, so for your current case you'd better merely doing something like this:

$keyword = $_GET['keyword'] ? $_GET['keyword'] : 'default_value';

In the other hand, if you want to still use filter_input() another simple alternative for default is:

$keyword = filter_input(INPUT_GET, 'keyword', FILTER_DEFAULT);
$keyword = $keyword ? $keyword : 'default_value';

Upvotes: 1

Related Questions