Detect if PHP session exists

前端 未结 5 1903
星月不相逢
星月不相逢 2020-11-30 03:23

Facebook now offer subscriptions to users so you can get realtime updates on changes. If my app receives an update, I plan to store it in the database. I would also like to

相关标签:
5条回答
  • 2020-11-30 03:26

    If you are on php 5.4+, it is cleaner to use session_status():

    if (session_status() == PHP_SESSION_ACTIVE) {
      echo 'Session is active';
    }
    
    • PHP_SESSION_DISABLED if sessions are disabled.
    • PHP_SESSION_NONE if sessions are enabled, but none exists.
    • PHP_SESSION_ACTIVE if sessions are enabled, and one exists.
    0 讨论(0)
  • 2020-11-30 03:29
    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();
    
    0 讨论(0)
  • 2020-11-30 03:33

    Which method is used to check if SESSION exists or not? Answer: isset($_SESSION['variable_name'])

    Example: isset($_SESSION['id'])

    0 讨论(0)
  • 2020-11-30 03:34

    According to the PHP.net manual:

    If $_SESSION (or $HTTP_SESSION_VARS for PHP 4.0.6 or less) is used, use isset() to check a variable is registered in $_SESSION.

    0 讨论(0)
  • 2020-11-30 03:50

    I use a combined version:

    if(session_id() == '' || !isset($_SESSION)) {
        // session isn't started
        session_start();
    }
    
    0 讨论(0)
提交回复
热议问题