Check if PHP session has already started

后端 未结 26 2064
醉酒成梦
醉酒成梦 2020-11-22 03:08

I have a PHP file that is sometimes called from a page that has started a session and sometimes from a page that doesn\'t have session started. Therefore when I have s

相关标签:
26条回答
  • 2020-11-22 03:52
    if (version_compare(PHP_VERSION, "5.4.0") >= 0) {
        $sess = session_status();
        if ($sess == PHP_SESSION_NONE) {
            session_start();
        }
    } else {
        if (!$_SESSION) {
            session_start();
        }
    }
    

    Actually, it is now too late to explain it here anyway as its been solved. This was a .inc file of one of my projects where you configure a menu for a restaurant by selecting a dish and remove/add or change the order. The server I was working at did not had the actual version so I made it more flexible. It's up to the authors wish to use and try it out.

    0 讨论(0)
  • 2020-11-22 03:52

    You can use the following solution to check if a PHP session has already started:

    if(session_id()== '')
    {
       echo"Session isn't Start";
    }
    else
    {
        echo"Session Started";
    }
    
    0 讨论(0)
  • 2020-11-22 03:52

    This is what I use to determine if a session has started. By using empty and isset as follows:

    if (empty($_SESSION)  && !isset($_SESSION))  {
        session_start();
    }
    
    0 讨论(0)
  • 2020-11-22 03:54

    Use session_id(), it returns an empty string if not set. It's more reliable than checking the $_COOKIE.

    if (strlen(session_id()) < 1) {
        session_start();
    }
    
    0 讨论(0)
  • 2020-11-22 03:54

    On PHP 5.3 this works for me:

    if(!strlen(session_id())){
        session_name('someSpecialName');
        session_start();
    } 
    

    then you have. If you do not put the not at if statement beginning the session will start any way I do not why.

    0 讨论(0)
  • 2020-11-22 03:55
    if (session_id() === "") { session_start(); }
    

    hope it helps !

    0 讨论(0)
提交回复
热议问题