Check if PHP session has already started

后端 未结 26 2060
醉酒成梦
醉酒成梦 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:33
    session_start();
    if(!empty($_SESSION['user']))
    {     
      //code;
    }
    else
    {
        header("location:index.php");
    }
    
    0 讨论(0)
  • 2020-11-22 03:35

    you can do this, and it's really easy.

    if (!isset($_SESSION)) session_start();
    

    Hope it helps :)

    0 讨论(0)
  • 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.

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

    Check this :

    <?php
    /**
    * @return bool
    */
    function is_session_started()
    {
        if ( php_sapi_name() !== 'cli' ) {
            if ( version_compare(phpversion(), '5.4.0', '>=') ) {
                return session_status() === PHP_SESSION_ACTIVE ? TRUE : FALSE;
            } else {
                return session_id() === '' ? FALSE : TRUE;
            }
        }
        return FALSE;
    }
    
    // Example
    if ( is_session_started() === FALSE ) session_start();
    ?>
    

    Source http://php.net

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

    PHP 5.4 introduced session_status(), which is more reliable than relying on session_id().

    Consider the following snippet:

    session_id('test');
    var_export(session_id() != ''); // true, but session is still not started!
    var_export(session_status() == PHP_SESSION_ACTIVE); // false
    

    So, to check whether a session is started, the recommended way in PHP 5.4 is now:

    session_status() == PHP_SESSION_ACTIVE
    
    0 讨论(0)
  • 2020-11-22 03:39

    For all php version

    if ((function_exists('session_status') 
      && session_status() !== PHP_SESSION_ACTIVE) || !session_id()) {
      session_start();
    }
    
    0 讨论(0)
提交回复
热议问题