Check if PHP session has already started

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

    The only thing you need to do is:

    <?php
    if(!isset($_SESSION))
    {
    session_start();
    }
    ?>
    
    0 讨论(0)
  • 2020-11-22 03:48

    This should work for all PHP versions. It determines the PHP version, then checks to see if the session is started based on the PHP version. Then if the session is not started it starts it.

    function start_session() {
      if(version_compare(phpversion(), "5.4.0") != -1){
        if (session_status() == PHP_SESSION_NONE) {
          session_start();
        }
      } else {
        if(session_id() == '') {
          session_start();
        }
      }
    }
    
    0 讨论(0)
  • 2020-11-22 03:48

    Replace session_start(); with:

    if (!isset($a)) {
        a = False;
        if ($a == TRUE) {
            session_start();
            $a = TRUE;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 03:49

    @ before a function call suppresses any errors that may be reported during the function call.

    Adding a @ before session_start tells PHP to avoid printing error messages.

    For example:

    Using session_start() after you've already printed something to the browser results in an error so PHP will display something like "headers cannot be sent: started at (line 12)", @session_start() will still fail in this case, but the error message is not printed on screen.

    Before including the files or redirecting to new page use the exit() function, otherwise it will give an error.

    This code can be used in all cases:

    
        <?php 
            if (session_status() !== PHP_SESSION_ACTIVE || session_id() === ""){
                session_start(); 
            }
        ?>
    
    
    0 讨论(0)
  • 2020-11-22 03:50

    Is this code snippet work for you?

    if (!count($_SESSION)>0) {
        session_start();
    }
    
    0 讨论(0)
  • 2020-11-22 03:52

    Not sure about efficiency of such solution, but this is from working project This is also used if you need to define the default language

       /**
        * Start session
        * Fall back to ukrainian language
        */
       function valid_session() {
        if(session_id()=='') {
            session_start();
            $_SESSION['lang']='uk';
            $_SESSION['lang_id']=3;
        }
        return true;
      }
    
    0 讨论(0)
提交回复
热议问题