How can you check if a PHP session exists?

前端 未结 11 1318
孤独总比滥情好
孤独总比滥情好 2021-02-04 06:11

Just wondering how to check if a PHP session exists... My understanding is that no matter what, if I am using sessions, I have to start my files with session_start() to even acc

相关标签:
11条回答
  • 2021-02-04 07:01

    isset($_SESSION) isn't sufficient because if a session has been created and destroyed (with session_destroy()) in the same execution, isset($_SESSION) will return true. And this situation may happen without your knowing about it when a 3rd party code is used. session_id() correctly returns an empty string, though, and can be called prior to session_start().

    0 讨论(0)
  • 2021-02-04 07:01

    I've always simply used

    if (@session_id() == "") @session_start();
    

    Hasn't failed me yet.

    Been quite a long time using this.

    NOTE: @ simply suppresses warnings.

    0 讨论(0)
  • 2021-02-04 07:02

    Check if session exists before calling session_start()

    if(!isset($_SESSION))session_start();
    
    0 讨论(0)
  • 2021-02-04 07:04

    Store the session_id in $_SESSION and check against it.

    First time

    session_start();
    $_SESSION['id'] = session_id();
    

    Starts a session and stores the randomly given session id.

    Next time

    session_start();
    $valid_session = isset($_SESSION['id']) ? $_SESSION['id'] === session_id() : FALSE;
    if (!$valid_session) {
       header('Location: login.php');
       exit();
    }
    

    Starts a session, checks if the current session id and the stored session id are identical (with the ternary ? as replacement for the non-existing short circuit AND in php). If not, asks for login again.

    0 讨论(0)
  • 2021-02-04 07:08

    In PHP there is something called the session name. The name is co-related to the cookie that will be being set if the session was already started.

    So you can check the $_COOKIE array if there is a session cookie available. Cookies are normally the preferred form to interchange the session id for the session name with the browser.

    If a cookie already exists this means that a PHP session was started earlier. If not, then session_start() will create a new session id and session.

    A second way to check for that is to check the outgoing headers if the cookie for the session is set there. It will be set if it's a new session. Or if the session id changed.

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