开发者

'true' in Get variables

开发者 https://www.devze.com 2023-01-10 00:37 出处:网络
In PHP, when you have something in the URL like \"var=true\" in the URL, does the \'true\' and \'false\' in the URL get translated to boolean variables, or do they e开发者_如何学Pythonqual the text \'

In PHP, when you have something in the URL like "var=true" in the URL, does the 'true' and 'false' in the URL get translated to boolean variables, or do they e开发者_如何学Pythonqual the text 'true' or 'false'? For instance, would, with the url having "var=false" in it:

if ($_GET['var'] == false) { ... }

work? Or would the variable always be true since it has text in it?


No, $_GET will always contain only strings.

However, you can filter it to get a boolean.

FILTER_VALIDATE_BOOLEAN:
Returns TRUE for "1", "true", "on" and "yes". Returns FALSE otherwise. If FILTER_NULL_ON_FAILURE is set, FALSE is returned only for "0", "false", "off", "no", and "", and NULL is returned for all non-boolean values.

Example:

$value = filter_input(INPUT_GET, "varname", FILTER_VALIDATE_BOOLEAN,
    array("flags" => FILTER_NULL_ON_FAILURE));


They are passed as strings, so are always truthy unless they are one of these, which evaluate to false instead:

  • The empty string ''
  • A string containing the digit zero '0'

To make my life easier I just pass boolean GET variables as 1 or 0 and validate them to be either one of those values, or decide on a default value appropriately:

// Default value of false
$var = false;

if (isset($_GET['var']))
{
    if ($_GET['var'] === '1' || $_GET['var'] === '0')
    {
        $var = (bool) $_GET['var'];
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消