Passing Boolean via PHP GET

Pretty simple question, but not sure about the answer. Can I pass a boolean variable through get? For instance:

http://example.com/foo.php?myVar=true

then i have

$hopefullyBool = $_GET['myVar'];

Is $hopefullyBoolboolean or string? My hypothesis is that this is a string, but can someone tell me about this? Thanks

+8
source share
4 answers

All GET parameters will be strings in PHP. Use filter_varand 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", "", NULL is returned for all non-boolean values.

$hopefullyBool = filter_var($_GET['myVar'], FILTER_VALIDATE_BOOLEAN);

boolean, , true false, 0 1:

http://example.com/foo.php?myVar=0
http://example.com/foo.php?myVar=1

:

$hopefullyBool = (bool)$_GET['myVar'];

true false, :

$hopefullyBool = $_GET['myVar'] == 'true' ? true : false;

, filter_var FILTER_VALIDATE_BOOLEAN .

+21

if:

filter_var('true', FILTER_VALIDATE_BOOLEAN);  
//bool(true)

filter_var('false', FILTER_VALIDATE_BOOLEAN); 
//bool(false)
+3

. bool cast, .

, myVar == "True"

:

>>> bool("foo")
True
>>> bool("")
False

False, True. - .

+2

. -, (boolean) PHP, :

$hopefullyBool = (boolean)$_GET['myVar'];

true false $_GET['myVar'].

5.2.1, json_decode() :

$hopefullyBool = json_decode($_GET['myVar]);

json_decode() JSON- ( ) PHP . 'true' URL true.

, :

$hopefullyBool = (boolean)json_decode($_GET['myVar]);

, URL ( strtolower() ?myVar=True ?myVar=FALSE), strtolower(), :

$hopefullyBool = (boolean)json_decode(strtolower($_GET['myVar]));

, false URL, PHP . isset():

$hopefullyBool = false;
if ( isset($_GET['myVar']) ) {
    $hopefullyBool = (boolean)json_decode(strtolower($_GET['myVar]));
}

, $hopefullyBool , :

$hopefullyBool = isset($_GET['myVar']) && (boolean)json_decode(strtolower($_GET['myVar']));

0

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


All Articles