Thursday, 3 August 2017

Passing a boolean through PHP GET



Pretty simple question here, not sure the answer though. Can I pass a boolean variable through get? For example:



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


then I have



$hopefullyBool = $_GET['myVar'];


Is $hopefullyBool a boolean or a string? My hypothesis is that it's a string but can someone let me know? Thanks


Answer



All GET parameters will be strings in PHP. Use filter_var and 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.




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


Another way to get the type boolean, pass as something that evaluates to true or false like 0 or 1:



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


Then cast to boolean:



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


If you want to pass string true or false then another way:



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


But I would say that filter_var with FILTER_VALIDATE_BOOLEAN was meant for this.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...