Joomla check for empty string with JInput

2019-05-06 15:59发布

问题:

Following this guide to sanitize my inputs, I'm wondering if an empty string is covered with this?

$jinput = JFactory::getApplication()->input;
$this->name = $jinput->get('name', '', 'STRING');

Typically without Joomla I'd be checking for an empty string as well. Something like:

if (!empty($_POST['name']))

Looking at the JInput get method I see that it checks if it is isset:

public function get($name, $default = null, $filter = 'cmd')
{
    if (isset($this->data[$name]))
    {
        return $this->filter->clean($this->data[$name], $filter);
    }

    return $default;
}

Not the same thing, as isset will only check for null. However that is the default value for using the get method. So if I specify an empty string for the second parameter am I covered here?

$this->name = $jinput->get('name', '', 'STRING');

回答1:

It's not up to Joomla to decide whether your empty string is valid value or not. They have to use isset(), because if they would use empty() and you return '0' which you would expect as normal, Joomla would return default value instead of that '0'.

So it's completely normal that they just use isset() to check if variable is set, and it's up to you to decide what values you accept.

If the value isn't set, and you set as the second parameter empty string '', you'll get an empty string returned.

In your example an empty string would be returned, which is expected behaviour.