简体   繁体   English

PHP会话错误未设置

[英]PHP session false not set

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. 我的PHP版本是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. 但是它当然不起作用,因为IsMobile为空布尔值。 (In original I just use IsMobile. IsMobile1 and IsMobile2 is just for testing). (最初我只是使用IsMobile。IsMobile1和IsMobile2仅用于测试)。

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. 由于boolean类型不能用作1或0的常量,因此它只是发生,因此在打印或任何其他输出尝试时将其强制转换为int But it only happens to the TRUE . 但这仅发生在TRUE FALSE always (or at least in most cases) stays empty (I've never seen a bool var output FALSE ). FALSE始终(至少在大多数情况下)保持为空(我从未见过bool var输出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). 但是,好消息是,如果在if语句中使用定义为FALSE的变量,它将被解释为FALSE (符合预期)。

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". 布尔TRUE值将转换为字符串“ 1”。 Boolean FALSE is converted to "" (the empty string). 布尔值FALSE转换为“”(空字符串)。 This allows conversion back and forth between boolean and string values. 这允许在布尔值和字符串值之间来回转换。

The source 来源

How about something like: 怎么样:

if (!empty($_SESSION["IsMobile"]))
{
  header("location: Mobile/");
  exit;
}

尝试使用严格运算符

$_SESSION['IsMobile'] === TRUE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM