Check if PHP session has already started

后端 未结 26 2080
醉酒成梦
醉酒成梦 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:37

    Prior to PHP 5.4 there is no reliable way of knowing other than setting a global flag.

    Consider:

    var_dump($_SESSION); // null
    session_start();
    var_dump($_SESSION); // array
    session_destroy();
    var_dump($_SESSION); // array, but session isn't active.
    

    Or:

    session_id(); // returns empty string
    session_start();
    session_id(); // returns session hash
    session_destroy();
    session_id(); // returns empty string, ok, but then
    session_id('foo'); // tell php the session id to use
    session_id(); // returns 'foo', but no session is active.
    

    So, prior to PHP 5.4 you should set a global boolean.

提交回复
热议问题