Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a boolean from a querystring?

How can I send a true or false value in a querystring and then use it in php? I'm trying to do as follows, but it gives me true even when both are set to false. I'll be getting these values from a htaccess file.

<?php
$var = $_GET['a'];
$bar = $_GET['b'];

if ($var && $bar)
{
echo "True";
}else
{
echo "False";
}

echo '<a href=?a=false&b=false>Check</a>';
?>
like image 593
Norman Avatar asked Feb 19 '23 07:02

Norman


1 Answers

They're both evaluating to True because you can't send a proper boolean true or false through a querystring. Both the strings "true" and "false" evaluate to TRUE in PHP. Either do:

if ($var == "true" && $bar == "true") {

or send 0 and 1 instead of "true" and "false" from your data source (I'm not entirely clear on how your .htaccess fits in here - I'm assuming it's massaging variables from a form field, but it's ultimately irrelevant.)

For more information, check out this incredibly massive table of PHP truth values. PHP's type coercion - that is to say, its method of turning arbitrary variables into variables of other types - is difficult to predict and operates upon its own logic.

That said, the querystring portion of the question isn't intrinsically a PHP problem - there's no canonical way to communicate booleans through GET or POST parameters. If you look, you'll notice that every site handles it their own way - some use "true", others 1, and yet others use TRUE.

There is one final alternative - JSON. Though it's unlikely to help in your case, my preferred method for exchanging data with the server is by encoding all the data into a single string of JSON. This has a few benefits such as giving me that fine-grained control over the variable types encapsulated in my JSON object, but it has the drawback of not being something you can do with a vanilla HTML form. Great if you're doing an AJAX-ey web app, though.

like image 92
Winfield Trail Avatar answered Mar 02 '23 19:03

Winfield Trail