问题
When setting false value to session, the session is set, but the value is empty. The type is boolean. This code:
<?php
session_start();
$_SESSION["IsMobile1"] = false;
$_SESSION["IsMobile2"] = true;
//header("location: ../../../index.php");
echo "IsSet1: " . isset($_SESSION["IsMobile1"]) . "; IsMobile1: " . $_SESSION["IsMobile1"] . "; type: " . gettype($_SESSION["IsMobile1"]) . ";<br>";
echo "IsSet2: " . isset($_SESSION["IsMobile2"]) . "; IsMobile2: " . $_SESSION["IsMobile2"] . ";<br>";
?>
prints out:
IsSet1: 1; IsMobile1: ; type: boolean;
IsSet2: 1; IsMobile2: 1;
My PHP version is 5.5.13. Is this expected behaviour? I am trying to read the session with code:
if (isset($_SESSION["IsMobile"]))
{
if (is_bool($_SESSION["IsMobile"]))
{
header("location: Mobile/");
exit;
}
}
but of course it is not working, because IsMobile is empty boolean. (In original I just use IsMobile. IsMobile1 and IsMobile2 is just for testing).
回答1:
I have faced this issue myself many times and, while still unconfirmed, I have come to this conclusion:
As boolean
type can't be used as constant for 1 or 0, it just happens so that it is cast to int
upon printing or any other output attempt. But it only happens to the TRUE
. FALSE
always (or at least in most cases) stays empty (I've never seen a bool
var output FALSE
).
But the good news in, if you use a variable defined as FALSE
in an if
statement, it will be interpreted as FALSE
(as expected).
So, what to do if you want to output them?
Output strings:
if ($_SESSION["IsMobile"] == FALSE) {
echo "FALSE";
}
UPDATE Oh yeah, here's what I missed in the docs:
A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string values.
The source
回答2:
How about something like:
if (!empty($_SESSION["IsMobile"]))
{
header("location: Mobile/");
exit;
}
回答3:
Try using the strict operator
$_SESSION['IsMobile'] === TRUE
来源:https://stackoverflow.com/questions/26982016/php-session-false-not-set